简体   繁体   中英

Converting ZonedDateTime to string

I need to store the current time as a String in a database. The time can be in different timezones, so I'm looking at using Java SE 8's new ZonedDateTime class.

I notice that the toString() method automatically outputs:

2016-04-15T17:40:49.305-05:00[America/Chicago]

This also seems to be readable by ZonedDateTime.parse() and convert to the right values.

If all I am doing is storing these values and I don't need to ever convert the value to a user-readable format, is this all I need to do to accurately store data with proper timezones? For example, if I insert two ZonedDateTimes into an SQL database by storing their toString() representations, and I later read in these times by using ZonedDateTime.parse(), can I expect things like isAfter() and isBefore() to work just fine?

Or am I missing a step in between? After trying to figure out timezones in Java 7 this feels almost too easy.

Yes, that will accurately store the date, and using the .parse() method will allow you to use the other methods of ZoneDateTime. Though if you want to be able to use sorting functions with your db then you will need to either manually convert the ZonedDateTime into a timestamp or use your ORM's features to do it for you.

Generally speaking I would avoid relying on parsing the toString() representation of any class in my application. toString() is meant to provide a human readable version of a class so it's subject to change from relase to release.

I would suggest you to force the format to be the one that you expect, eg applying:

String toStoreInDb = DateTimeFormatter.ISO_ZONED_DATE_TIME.format(zonedDateTime);
...
ZonedDateTime fromDb = 
ZonedDateTime.parse(stringFromDb, DateTimeFormatter.ISO_ZONED_DATE_TIME);

This way your application will resist to any toString() change. Moreover take a look at this bug: Bug in ZonedDateTime.parse()

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM