Created
February 24, 2016 16:21
-
-
Save diamondo25/526f6b004291fedadf10 to your computer and use it in GitHub Desktop.
Parsing (from and to) WCF DateTime json input to joda DateTime
This file contains 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
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