Skip to content

Instantly share code, notes, and snippets.

@alexanderfefelov
Created July 20, 2018 00:33
Show Gist options
  • Save alexanderfefelov/af4cbc67b30063f32a81893e07c78287 to your computer and use it in GitHub Desktop.
Save alexanderfefelov/af4cbc67b30063f32a81893e07c78287 to your computer and use it in GitHub Desktop.
Decode Joda DateTime with circe
import io.circe.generic.auto._
import io.circe._
import io.circe.parser._
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import scala.util.control.NonFatal
object CirceDateTimeDecoder extends App {
val dateFormatter = DateTimeFormat.forPattern("yyyyMMdd")
implicit val decodeDateTime: Decoder[DateTime] = Decoder.decodeString.emap { s =>
try {
Right(DateTime.parse(s, dateFormatter))
} catch {
case NonFatal(e) => Left(e.getMessage)
}
}
case class Model(date: DateTime)
val str = """{"date": "20180101"}"""
val data: Either[Error, Model] = decode[Model](str)
data match {
case Right(model) => println(model)
case Left(e) => System.err.println(e)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment