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)
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.