我认为2011-10-23 12:00:00
将与UTC
保持相同,并且转换日期
将是<强>2011-10-23 17:00:00
。
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dt = formatter.parse("2011-10-23 12:00:00");
LocalDateTime ldt = new DateTime(dt).withZone(DateTimeZone.UTC).toLocalDateTime();
LOGGER.warn("Original date: " + ldt.toDateTime().toDate().toString());
DateTime cvtldt = ldt.toDateTime(DateTimeZone.forID("-05:00"));
LOGGER.warn("Converted date: " + cvtldt.toLocalDateTime().toDateTime().toDate().toString());
我不明白为什么输出是负一小时?
Original date: Sun Oct 23 11:00:00 BST 2011
Converted date: Sun Oct 23 11:00:00 BST 2011
最佳答案
您正在使用Date.toString()
始终使用本地时区。看看你的字符串如何包含“BST”?
理想情况下,尽可能多地坚持使用 Joda Time:
- 使用 Joda 时间格式化程序进行解析
- 不要转换回
Date
除非你需要 - 不要使用
Date.toString()
如果你可以可能避免它;您无法控制其格式。
尚不清楚您真正想要实现的目标是什么,但几乎可以肯定您不想进行这么多转换。例如,您调用 toLocalDateTime()
接下来是 toDateTime()
再次 - 这意味着在您在之前的转换中仔细指定 UTC 之后,它正在使用系统默认时区...
您的代码包含以下转换(按此顺序):
- 字符串到日期
- 日期到日期时间
- 日期时间到 UTC 日期时间
- 日期时间到本地日期时间 (*)
- 本地日期时间到日期时间
- 日期时间至今
- 日期转字符串
- (从 * 处的结果)LocalDateTime 到 DateTime
- 日期时间到本地日期时间
- 本地日期时间到日期时间
- 日期时间至今
- 日期转字符串
您认为所有这些转换既必要又正确指定的可能性有多大? ;)
关于java - 为什么 "12:00"转换为 UTC 会变成 "11:00"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7868105/