Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
174
rated 0 times [  181] [ 7]  / answers: 1 / hits: 23743  / 10 Years ago, mon, february 24, 2014, 12:00:00

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> {
@Override
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?


More From » java

 Answers
14

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.


[#72347] Saturday, February 22, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleyaleenag

Total Points: 678
Total Questions: 121
Total Answers: 105

Location: Papua New Guinea
Member since Thu, Jul 9, 2020
4 Years ago
harleyaleenag questions
Thu, May 5, 22, 00:00, 2 Years ago
Wed, Aug 19, 20, 00:00, 4 Years ago
;