Best practice to Serialize java.time.LocalDateTime (java 8) to js Date using GSON

In our recent project we use java 8. I need to serialize java.time.LocalDateTime to java script Date format.

Currently what I did was define a custom serializer to convert LocalDateTime to timestamp.

public class LocalDateTimeSerializer implements JsonSerializer<LocalDateTime> {
    public JsonElement serialize(LocalDateTime localDateTime, Type type, JsonSerializationContext jsonSerializationContext) {
        Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
        Date date = Date.from(instant);
        return new JsonPrimitive(date.getTime());

then create Gson object using GsonBuilder with my custom LocalDateTimeSerializer

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer());

Gson gson = gsonBuilder.create();

Then in Java Script I create a Date object using this time stamp. It's working fine.

I need to know, is this way ok or is there a better way to do this?



YES, that's the best way.

It's highly recommended to convert a Time object into it's long type representation when you're going to transfer it from one system to another. This can avoid many problems, such as data formatting and time local in different systems.

And what's more, long representation takes only 8 bytes, while string representation takes a little more. Which means long representation is more efficient to transfer and parse.


Java 8 solution from LocalDateTime to Epoch Milliseconds or Seconds:

// to Epoch Seconds
long sec = localDateTime.toInstant(ZoneOffset.UTC).getEpochSecond();

// to Epoch Milliseconds
long msec = localDateTime.toInstant(ZoneOffset.UTC).toEpochMilli();

In your case however I see a bug which uses Local Timezone instead of UTC. My recommended solution would be:

public JsonElement serialize(LocalDateTime localDateTime, Type type, JsonSerializationContext jsonSerializationContext) {
    long sec = localDateTime.toInstant(ZoneOffset.UTC).getEpochSecond();
    return new JsonPrimitive(sec);


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.