Skip to content

Instantly share code, notes, and snippets.

@diamondo25
Created February 24, 2016 16:21
Show Gist options
  • Save diamondo25/526f6b004291fedadf10 to your computer and use it in GitHub Desktop.
Save diamondo25/526f6b004291fedadf10 to your computer and use it in GitHub Desktop.
Parsing (from and to) WCF DateTime json input to joda DateTime
private val microsoftDateWithTZ = """\/Date\(([0-9]+)([\-\+])([0-9]{2})([0-9]{2})\)\/""".r
private val microsoftDateWithoutTZ = """\/Date\(([0-9]+)\)\/""".r
implicit val jodaDateTimeReads = Reads[DateTime]({
case JsString(microsoftDateWithoutTZ(ticks)) =>
JsSuccess(new DateTime(ticks.toLong))
case JsString(microsoftDateWithTZ(ticks, upOrDown, hours, minutes)) =>
val hoursInt = hours.dropWhile(_ == '0').toIntOpt.getOrElse(0)
val minutesInt = minutes.dropWhile(_ == '0').toIntOpt.getOrElse(0)
val tz =
if (upOrDown == "+") {
DateTimeZone.forOffsetHoursMinutes(hoursInt, minutesInt)
} else {
DateTimeZone.forOffsetHoursMinutes(-hoursInt, minutesInt)
}
JsSuccess(new DateTime(ticks.toLong, tz))
case JsString(text) => JsError(s"This is not a valid datetime: $text")
})
implicit val jodaDateTimeWrites = Writes[DateTime](x => {
JsString("/Date(" + x.withZone(DateTimeZone.UTC).getMillis + "-0000)/")
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment