Created
October 10, 2024 10:08
-
-
Save pietersp/4babe77eaeada3ed7d7367803d017847 to your computer and use it in GitHub Desktop.
Play around with instant json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//> using scala 2.13.15 | |
//> using dep "com.typesafe.play::play-json:2.10.6" | |
import play.api.libs.json.JsValue | |
import java.time.{Instant, ZoneId, ZoneOffset} | |
import play.api.libs.json.{Json, OFormat} | |
val actualInstant = Instant.parse("2022-01-01T00:00:00Z") | |
val timestamps = """ | |
[ | |
{"timestamp": "2022-01-01T00:00:00Z"}, | |
{"timestamp": "2022-01-01T00:00:00.000Z"}, | |
{"timestamp": "2022-01-01T00:00:00+00:00"}, | |
{"timestamp": "2022-01-01T02:00:00+02:00"}, | |
{"timestamp": "2022-01-01T02:00:00.000+02:00"}, | |
{"timestamp": "2022-01-01T02:00:00+02:00[Africa/Johannesburg]"} | |
] | |
""" | |
case class MyTimeStamp(timestamp: Instant) | |
implicit val format: OFormat[MyTimeStamp] = Json.format[MyTimeStamp] | |
val unmarshalled: List[MyTimeStamp] = Json | |
.parse(timestamps) | |
.as[List[MyTimeStamp]] | |
val marshalled: JsValue = Json.toJson(unmarshalled) | |
println("--- Unmarshalled ---") | |
unmarshalled.foreach(println) | |
println("--- Epoch Seconds ---") | |
unmarshalled.map(_.timestamp.getEpochSecond()).foreach(println) | |
println("--- To ZonedDateTime (Johannesburg)---") | |
unmarshalled.map(_.timestamp.atZone(ZoneId.of("Africa/Johannesburg"))).foreach(println) | |
println("--- To ZonedDateTime (+02:00) ---") | |
unmarshalled.map(_.timestamp.atZone(ZoneOffset.of("+02:00"))).foreach(println) | |
println("--- Are all equal to original ---") | |
println(unmarshalled.forall(_.timestamp == actualInstant)) | |
println("--- Re marshalled ---") | |
println(marshalled.toString()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: