Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 316
rAJ Avatar asked Jan 21 '26 15:01

rAJ


1 Answers

Running Groovy on Java 8 gives you access to the much better Date/Time classes... You can just do:

import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit

String result = ZonedDateTime.parse("2017-12-18T20:41:06.136Z")
    .truncatedTo(ChronoUnit.DAYS)
    .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
like image 134
tim_yates Avatar answered Jan 23 '26 05:01

tim_yates