问题
In Central Europe, the current time zone (as of 3rd October) is:
CEST / UTC+2
But when I create an instance of SimpleDateFormat in Android now ...
dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
... 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?
Furthermore, when using the (now deprecated) method getTimezoneOffset() of Date instances, it returns inconsistent results:
(new Date()).getTimezoneOffset() correctly returns -120 (2 hours) while dateTimeFormat.parse("2012-10-03T22:00:00.000+0000").getTimezoneOffset() returns -60 (1 hour).
How can this happen? Am I doing something wrong or is this a known bug?
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.
回答1:
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
回答2:
I have just switched to JODA with is great.
It also works good on Android with the comments in this link: Android Java - Joda Date is slow That make it run faster.
来源:https://stackoverflow.com/questions/12715216/simpledateformat-ignoring-dst-offset-in-android