我将我的项目放在托管中,其时区与我的位置不同。
在我的Web项目中,我使用“Timestamp”将时间插入到我的数据库中。所以我需要得到芝加哥的时间(我的时区)。
我使用jode time来获取不同时区的时间。
我的代码如下:
DateTime dt = new DateTime();
DateTime dtChicago =dt.withZone(DateTimeZone.forID("America/Chicago"));
java.sql.Timestamp timeStamp = new java.sql.Timestamp(dtChicago.getMillis());
然而,当我测试它时,我发现以下打印的时间相同毫秒
DateTime dtLondon = dt.withZone(DateTimeZone.forID("Europe/London"));
System.out.println(dtLondon.getMillis());
DateTime dtChicago = dt.withZone(DateTimeZone.forID("America/Chicago"));
System.out.println(dtChicago.getMillis());
那么我怎样才能获得确切的“芝加哥”时区时间并将其注入时间戳?
答案 0 :(得分:2)
I found the follows print the same milliseconds
这对你没有意义吗?我现在所处的时间可能与您所在的时间不同,但自Unix epoch 是一样的。
时间戳是时间量。它没有时区概念。您可以直接存储它。
当您需要对其进行格式化以向用户显示时,您将提供时区,转换将负责执行时区的时差。
答案 1 :(得分:0)
您不能将TimeZone放入Timestamp对象中。与数据库交互时,您需要为Calendar
和PreparedStatement
中的ResultSet
提供Calendar
{{1}}。需要将{{1}}设置为您希望数据存储在数据库中的TimeZone。将所有数据规范化为UTC对于处理来自多个时区的数据具有许多优点。它还消除了重复一个小时后由DST引起的“模糊时间”。
答案 2 :(得分:0)
您可以使用DateTimeZone::convertUTCToLocal方法获取指定时区的时间
long europeMillis = DateTimeZone.forID("Europe/London").convertUTCToLocal(dt.getMillis());
long americaMillis = DateTimeZone.forID("America/Chicago").convertUTCToLocal(dt.getMillis());