Skip to content

Instantly share code, notes, and snippets.

@jeffsheets
Created September 26, 2018 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffsheets/938733963c03208afd74927fb6130884 to your computer and use it in GitHub Desktop.
Save jeffsheets/938733963c03208afd74927fb6130884 to your computer and use it in GitHub Desktop.
Groovy Jackson Deserializer to convert a .NET style JSON dateTime to a Java LocalDateTime object
class JsonDotNetLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
@Override
LocalDateTime deserialize(JsonParser parser, DeserializationContext ctxt) {
convertDotNetDateToJava(parser.text.trim())
}
/**
* Returns a Java LocalDateTime when given a .Net Date String
* /Date(1535491858840-0500)/
*/
static LocalDateTime convertDotNetDateToJava(String dotNetDate) {
// Strip the prefix and suffix to just 1535491858840-0500
String epochAndOffset = dotNetDate[6..-3]
// 1535491858840
String epoch = epochAndOffset[0..-6]
// -0500 Note, keep the negative/positive indicator
String offset = epochAndOffset[-5..-1]
ZoneId zoneId = ZoneId.of("UTC${offset}")
LocalDateTime.ofInstant(Instant.ofEpochMilli(epoch.toLong()), zoneId)
}
}
//Yeah imports at bottom are weird, but avoids them cluttering the gist
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
class JsonDotNetLocalDateTimeDeserializerSpec extends Specification {
@Unroll
def "test convertDotNetDateToJava for #dotNetDate"(String dotNetDate, String expected) {
expect:
convertDotNetDateToJava(dotNetDate) == LocalDateTime.parse(expected)
where:
dotNetDate || expected
'/Date(1535491858840-0500)/' || '2018-08-28T16:30:58.840'
'/Date(1535491858840+0500)/' || '2018-08-29T02:30:58.840'
'/Date(1535491858840-0000)/' || '2018-08-28T21:30:58.840'
'/Date(1535491858840-0430)/' || '2018-08-28T17:00:58.840'
}
}
import spock.lang.Specification
import spock.lang.Unroll
import java.time.LocalDateTime
import static JsonDotNetLocalDateTimeDeserializer.convertDotNetDateToJava
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment