user10829672
user10829672

Reputation: 39

How to change a given date in "yyyy-MM-dd HH:mm:ss.SSS" format to "yyyy-MM-dd'T'HH:mm:ss.SSS'Z" format in groovy

How to convert a given date in yyyy-MM-dd HH:mm:ss.SSS format to yyyy-MM-dd'T'HH:mm:ss.SSS'Z' format in groovy For example, the given date is 2019-03-18 16:20:05.6401383. I want it to converted to 2019-03-18T16:20:05.6401383Z

This is the code Used:

 def date = format1.parse("2019-03-18 16:20:05.6401383");
 String settledAt = format2.format(date)
 log.info ">>> "+*date*+"   "+*settledAt*

The result, where the date is getting changed somehow: Mon Mar 18 18:06:46 EDT 2019 & 2019-03-18T18:06:46.383Z

Thanks in advance for all the answers.

Upvotes: 0

Views: 2943

Answers (2)

bdkosher
bdkosher

Reputation: 5883

If you're on Java 8+ and Groovy 2.5+, I would use the new Date/Time API:

import java.time.*

def date = LocalDateTime.parse('2019-03-18 16:20:05.6401383', 'yyyy-MM-dd HH:mm:ss.nnnnnnn')
String settledAt = date.format(/yyyy-MM-dd'T'HH:mm:ss.nnnnnnn'Z'/)

This is presuming the input date has a "Zulu" time zone.

Upvotes: 1

daggett
daggett

Reputation: 28634

it's a feature of java

def date = Date.parse("yyyy-MM-dd HH:mm:ss.SSS","2019-03-18 16:20:05.6401383")

returns

Mon Mar 18 18:06:46 EET 2019

the problem that java handles only milliseconds SSS (3 digits after seconds)

but you are providing 7 digits for milliseconds 6401383

as workaround remove extra digits with regexp:

def sdate1 = "2019-03-18 16:20:05.6401383"
sdate1 = sdate1.replaceAll( /\d{3}(\d*)$/, '$1') //keep only 3 digits at the end
def date = Date.parse("yyyy-MM-dd HH:mm:ss.SSS",sdate1)
def sdate2 = date.format("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")

Upvotes: 0

Related Questions