SimpleDateFormat的忽视DST在Android的偏移 [英] SimpleDateFormat ignoring DST offset in Android
问题描述
在中欧,当前时区(截至10月3日的)是:
In Central Europe, the current time zone (as of 3rd October) is:
CEST / UTC + 2
CEST / UTC+2
但是当我创建一个Android的的SimpleDateFormat
的实例现在...
But when I create an instance of SimpleDateFormat
in Android now ...
dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
...返回 CET / UTC + 1
的时区。因此它忽略了DST偏移量必须仍然存在的时刻。这是为什么?
... it returns CET / UTC+1
as the time zone. So it's ignoring the DST offset which must still be there at the moment. Why is this?
此外,使用(现德precated)方法时,使用getTimezoneOffset()
日期
的情况下,它返回不一致的结果:
Furthermore, when using the (now deprecated) method getTimezoneOffset()
of Date
instances, it returns inconsistent results:
(新的Date())。使用getTimezoneOffset()
正确返回-120(2小时),而 dateTimeFormat.parse(2012-10- 03T22:00:。00.000 + 0000)使用getTimezoneOffset()
返回-60(1小时)
(new Date()).getTimezoneOffset()
correctly returns -120 (2 hours) while dateTimeFormat.parse("2012-10-03T22:00:00.000+0000").getTimezoneOffset()
returns -60 (1 hour).
怎么能这样呢?我是不是做错了什么或者这是一个已知的bug?
How can this happen? Am I doing something wrong or is this a known bug?
注意:我听说有哪个提供更好的时间计算(如乔达时间)库,并且我听说经常现在;),但使用一些解决方法,你可以因为很方便地使用内置的Java时库。
Note: I've heard that there are libraries which offer better time calculations (e.g. Joda Time), and I've heard that quite often now ;) But using some workarounds, you can just as easily use the built-in Java time library.
和,当然,时区正确地在我的机器上设置的。
And, of course, the timezone is correctly set on my machine.
推荐答案
我不知道我是否正确地理解你的使用情况,但是从当我尝试这个code我所了解。
I don't know if I have properly understood your use case, but from what I have understood when I try this code.
public static void main(String[] args) {
SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String date="2012-10-03T22:00:00.000+0000";
try {
System.out.println(dateTimeFormat.getTimeZone().getDisplayName());
System.out.println("Today : "+new Date().toString()+ ", Timezone Offset :" +
+(new Date()).getTimezoneOffset());
System.out.println("Parsed Date : "+
dateTimeFormat.parse(date).toString()
+ ", Timezone Offset : "
+dateTimeFormat.parse(date).getTimezoneOffset());
} catch (ParseException e) {
e.printStackTrace();
}
}
我得到一个一致的输出即:
I am getting an consistent Output i.e :
Central European Time
Today : Wed Oct 03 09:44:56 CEST 2012, Timezone Offset : -120
Parsed Date : Wed Oct 03 23:00:00 CEST 2012, Timezone Offset : -120
这篇关于SimpleDateFormat的忽视DST在Android的偏移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!