Converting ZonedDateTime to string

前端 未结 2 1191
抹茶落季
抹茶落季 2021-01-25 06:20

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 noti

2条回答
  •  伪装坚强ぢ
    2021-01-25 06:41

    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, e.g 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()

提交回复
热议问题