将ZonedDateTime转换为字符串 [英] Converting ZonedDateTime to string

查看:593
本文介绍了将ZonedDateTime转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将当前时间作为字符串存储在数据库中.时间可以在不同的时区,所以我正在研究使用Java SE 8的新ZonedDateTime类.

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.

我注意到toString()方法自动输出:

I notice that the toString() method automatically outputs:

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

这似乎也可以被ZonedDateTime.parse()读取并转换为正确的值.

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

如果我所做的只是存储这些值,而无需将其转换为用户可读的格式,那么我是否需要做这些所有操作以准确存储具有适当时区的数据?例如,如果我通过存储它们的toString()表示形式将两个ZonedDateTimes插入SQL数据库中,后来又通过使用ZonedDateTime.parse()来读取这些时间,我是否可以期望isAfter()和isBefore()之类的东西能够正常工作好吗?

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?

还是我错过了两者之间的一步?在尝试弄清楚Java 7中的时区之后,这感觉太简单了.

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

推荐答案

是的,它将准确地存储日期,并且使用.parse()方法将允许您使用ZoneDateTime的其他方法.尽管如果您希望能够对数据库使用排序功能,那么您将需要手动将ZonedDateTime转换为时间戳,或者使用ORM的功能为您完成.

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.

这篇关于将ZonedDateTime转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆