tomhier
tomhier

Reputation: 580

Play JSON looses time info on deserialise

I have the following code:

val test = Json.parse("""{"someDate":"1998-10-18T10:00:00+03:00"}""")
val aDate = (test \ "someDate").as[Date]
val activationDate = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZZ").parseDateTime("1998-10-18T10:00:00+03:00").toDate
assert(aDate.compareTo(activationDate) == 0)

But the dates never compare, actually the 'aDate' has lost it's time info. Anyone here has an answer to me to resolve this?

Upvotes: 0

Views: 35

Answers (1)

Jerry
Jerry

Reputation: 492

As you have seen, the date info is lost when formatted from json. Though I don't know why, I can give an alternative solution to fix your problem. We can know that the string parsed from json will keep all its info. so you can parse the json data to be a String but not a Date and then format the parsed String to be what you want. The code is following

val aDateString = (test \ "someDate").as[String]//not Date

then, format it as usual String to Date

val aDate = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZZ").
            parseDateTime(aDateString).toDate//parse the string parsed from json

At this time,

assert(aDate.compareTo(activationDate) == 0)

will return the right answer.

Because aDateString is parsed from json does not lost info, you can implement what you want

Maybe, my solution is not the best, but it can guarantee the date info does not be lost

The blog maybe help you

Good luck

Upvotes: 1

Related Questions