0

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.

cfrick
  • 35,203
  • 6
  • 56
  • 68
user10829672
  • 35
  • 2
  • 10

2 Answers2

1

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.

bdkosher
  • 5,753
  • 2
  • 33
  • 40
  • Thanks, bdkosher, but did not work as is. However, I figured the way to make it work, based on LocalDateTime.parse. – user10829672 Mar 21 '19 at 16:43
  • @user10829672 If you have a working solution for your problem, it's OK to add your own answer (and even vote it). It will help others that find the question. – cfrick Mar 21 '19 at 20:33
0

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'")
daggett
  • 26,404
  • 3
  • 40
  • 56