rAJ rAJ - 11 months ago 172
Groovy Question

Parse date to "yyyy-MM-dd'T'00:00:00" using Groovy

I am trying to parse date format '2017-12-18T20:41:06.136Z' into "2017-12-18'T'00:00:00"

Date date = new Date();
def dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
dateformat.setTimeZone(TimeZone.getTimeZone(TimeZoneCode));
def currentDate = dateformat.format(date)
log.info "Current Date : " + currentDate
date1 = new SimpleDateFormat("yyyy-MM-dd'T'00:00:00").parse(currentDate)
log.info "Current Date : " + date1


Error displayed :


java.text.ParseException: Unparseable date: "2017-12-18T20:46:06:234Z" error at line: 16


This line gives error :

date1 = new SimpleDateFormat("yyyy-MM-dd'T'00:00:00").parse(currentDate)

Rao Rao
Answer Source

In order to avoid the mentioned error, use below statement Date.parse(..):

def dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
def dateString = "2017-12-18T20:41:06.136Z"
def date = Date.parse(dateFormat, dateString)

You should be able to achieve what you are trying to using below script.

//Change timezone if needed 
def tz = 'IST'  
TimeZone.setDefault(TimeZone.getTimeZone(tz))

def dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
def dateString = "2017-12-18T20:41:06.136Z"

Calendar calendar = Calendar.getInstance()
calendar.with {
  time = Date.parse(dateFormat,dateString)
  set(Calendar.HOUR_OF_DAY, 0)
  set(Calendar.MINUTE, 0)
  set(Calendar.SECOND, 0)     
  set(Calendar.MILLISECOND, 0)
}
log.info calendar.time.format(dateFormat)

You can quickly try the same online demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download