1

I am currently trying to store some database objects which contain timestamps into a graphical database (dgraph). I would like to use JSON to easily take date and time information and store it in a datetime node in the graph, but the graph will only accept data that is formatted in RFC 3339 format with an optional timezone (ex 2006-01-02T15:04:05.999999999).

I have been using Gson to serialize and de-serialize and other data types work fine, but trying to query the dates returns null. I have tried using setDateFormat but that doesn't seem to change anything. I currently have the timestamps stored in a LocalDateTime class, but can change that if need be.

How can I force Gson to use the correct format with my timestamps? It currently puts them in this format

"start":{
  "date":{"year":2011,"month":1,"day":2},
  "time":{"hour":10,"minute":4,"second":0,"nano":0}
}

I'm new to serializing and JSON in general so any pointers would be appreciated.

I've realized that gson seems to be separating my timestamp into two separate data chunks, How can I force it to keep them together in the correct format? Do I need a type adapter? (I don't know how they work)

Community
  • 1
  • 1
nootroot
  • 11
  • 1
  • Please update your question with model class and code for reading data from database and converting to model object. – Smile Jan 28 '20 at 05:09

1 Answers1

1

If you're fine with using a library, Joda Time offers a simple solution:

Serialization

DateTime dt = new DateTime(2006, 1, 2, 15, 4, 5, 999, DateTimeZone.UTC);
System.out.println(dt);

-------- OUTPUT --------
2006-01-02T15:04:05.999Z

Deserialization

DateTime dt = DateTime.parse("2006-01-02T15:04:05.999Z");
System.out.println(dt);

-------- OUTPUT --------
2006-01-02T15:04:05.999Z

As for the standard lib: When dealing with time zones, you'd use ZonedDateTime rather than LocalDateTime.

Julian Durchholz
  • 352
  • 3
  • 12