Skip to content

Instantly share code, notes, and snippets.

@pietersp
Created October 10, 2024 10:08
Show Gist options
  • Save pietersp/4babe77eaeada3ed7d7367803d017847 to your computer and use it in GitHub Desktop.
Save pietersp/4babe77eaeada3ed7d7367803d017847 to your computer and use it in GitHub Desktop.
Play around with instant json
//> 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())
@pietersp
Copy link
Author

Output:

--- Unmarshalled ---
MyTimeStamp(2022-01-01T00:00:00Z)
MyTimeStamp(2022-01-01T00:00:00Z)
MyTimeStamp(2022-01-01T00:00:00Z)
MyTimeStamp(2022-01-01T00:00:00Z)
MyTimeStamp(2022-01-01T00:00:00Z)
MyTimeStamp(2022-01-01T00:00:00Z)
--- Epoch Seconds ---
1640995200
1640995200
1640995200
1640995200
1640995200
1640995200
--- To ZonedDateTime (Johannesburg)---
2022-01-01T02:00+02:00[Africa/Johannesburg]
2022-01-01T02:00+02:00[Africa/Johannesburg]
2022-01-01T02:00+02:00[Africa/Johannesburg]
2022-01-01T02:00+02:00[Africa/Johannesburg]
2022-01-01T02:00+02:00[Africa/Johannesburg]
2022-01-01T02:00+02:00[Africa/Johannesburg]
--- To ZonedDateTime (+02:00) ---
2022-01-01T02:00+02:00
2022-01-01T02:00+02:00
2022-01-01T02:00+02:00
2022-01-01T02:00+02:00
2022-01-01T02:00+02:00
2022-01-01T02:00+02:00
--- Are all equal to original ---
true
--- Re marshalled ---
[{"timestamp":"2022-01-01T00:00:00Z"},{"timestamp":"2022-01-01T00:00:00Z"},{"timestamp":"2022-01-01T00:00:00Z"},{"timestamp":"2022-01-01T00:00:00Z"},{"timestamp":"2022-01-01T00:00:00Z"},{"timestamp":"2022-01-01T00:00:00Z"}]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment