Parsing a JSON string to a date

Hi all,

I have a question relating to parsing a JSON response using jsonSlurper to a date, so I can compare the date to get a test pass / fail result.

JSON date / time returned is in this format ‘2019-02-04T12:01:08.397106+00:00’ and the code I am currently experimenting with is below:

	def firstEventTime
	def parsedDate
	rowData.eachWithIndex({ def row, def i ->
		if (i == 0) {
			row = new JsonBuilder(row).toPrettyString()
			def jsonResponse = row
			def jsonSlurper = new JsonSlurper()
			Map parsedJson = jsonSlurper.parseText(jsonResponse)
			firstEventTime = parsedJson.get("time")
			println(firstEventTime)
			parsedDate = Date.parse("dd-MM-yyyy", firstEventTime)
		}

Returned value is ‘Sun Aug 11 00:00:00 GMT 9’. Which is not what I expected.

Does anyone have any experience of this?

Thank you!

Ross

Hey @ross.macdonald

Take a look here: http://docs.groovy-lang.org/latest/html/groovy-jdk/java/util/Date.html

Look at clearTime and format methods.

Hope that moves you forward?

1 Like

Thanks a lot for your response Russ! really appreciated. My solution was to expand the string comparison!

parsedFirstDateTime = Date.parse(“yyyy-MM-dd’T’HH:mm:ss”, firstEventDateTime)

Thanks again!

1 Like

The JSON specification does not specify a format for exchanging dates which is why there are so many different ways to do it. JSON does not know anything about dates. What .NET does is a non-standard hack/extension. The problem with JSON date and really JavaScript in general – is that there’s no equivalent literal representation for dates. In JavaScript following Date constructor straight away converts the milliseconds since 1970 to Date as follows:

var jsonDate = new Date(1297246301973);

Then let’s convert it to js format:

var date = new Date(parseInt(jsonDate.substr(6)));

The substr() function takes out the /Date( part, and the parseInt() function gets the integer and ignores the )/ at the end. The resulting number is passed into the Date constructor .

For ISO-8601 formatted JSON dates, just pass the string into the Date constructor:

var date = new Date(jsonDate);

Welcome to the forum.

The JavaScript Date() constructor returns a JavaScript Date Object. That being the case, it doesn’t have a substr() method (which works on strings). Therefore, that code will not function the way you describe:

image

Since this thread is ~3 years old, I’m closing it.