Date

December 22, 2017

sbt configuration

/***
libraryDependencies += "io.argonaut" %% "argonaut" % "6.2.2"
*/

Common imports

import argonaut._
import argonaut.Argonaut._
import java.text.SimpleDateFormat
import java.util.Date
import java.util.TimeZone

A date to be coded using ISO 8601

val now: Date = new Date(1545464936755L)
val iso8601 = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" // Used by JavaScript

Encoding

implicit val encodeDate: EncodeJson[Date] =
  EncodeJson { d =>
    val df: SimpleDateFormat = new SimpleDateFormat(iso8601)
    df.setTimeZone(TimeZone.getTimeZone("UTC"))
    jString(df.format(d))
  }

val encodedDate: String = now.asJson.spaces2

println(s"\nencoded Date:\n$encodedDate")

Decoding

implicit val decodeDate: DecodeJson[Date] =
  optionDecoder( _.string flatMap { s =>
                   val df: SimpleDateFormat =
                     new SimpleDateFormat(iso8601)
                   df.setTimeZone(TimeZone.getTimeZone("UTC"))
                   tryTo(df.parse(s))
                 }
               , "Date"
               )

val decodedDate: Either[String, Date] =
  "\"2018-12-22T07:48:56.755Z\"".decodeEither[Date]

println(s"\ndecoded Date:\n$decodedDate")

Demo

This file is literate Scala, and can be run using Codedown:

$ curl -s https://earldouglas.com/posts/reference/argonaut/date.md |
  codedown scala > script.scala
$ sbt -Dsbt.main.class=sbt.ScriptMain script.scala

encoded Date:
"2018-12-22T07:48:56.755Z"

decoded Date:
Right(Sat Dec 22 00:48:56 MST 2018)