title: Best practice to Serialize java.time.LocalDateTime (java 8) to js Date using GSON
body: <p>In our recent project we use java 8. I need to serialize java.time.LocalDateTime to java script Date format. </p>
  
  <p>Currently what I did was define a custom serializer to convert LocalDateTime to timestamp.</p>
  
  <pre><code>public class LocalDateTimeSerializer implements JsonSerializer&lt;LocalDateTime&gt; {
      @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());
      }
  }
  </code></pre>
  
  <p>then create Gson object using GsonBuilder with my custom LocalDateTimeSerializer</p>
  
  <pre><code>GsonBuilder gsonBuilder = new GsonBuilder();
  gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer());
  
  Gson gson = gsonBuilder.create();
  </code></pre>
  
  <p>Then in Java Script I create a Date object using this time stamp. It's working fine. </p>
  
  <p>I need to know, is this way ok or is there a better way to do this?  </p>