Java DateFormat parse() doesn’t respect the timezone

602

Ví dụ: cách chuyển đổi format, không phục thuộc vào local time zone

Kết quả:

2011-09-24 14:10:51 -0400

Sat Sep 24 20:10:51 CEST 2011

Giải thích:

It’s messy but necessary since parse() doesn’t return a value that preserves timezone and format() doesn’t accept a value that defines a timezone (the Date class).

DateFormat.parse() is NOT a query (something that returns a value and doesn’t change the state of the system). It is a command which has the side-effect of updating an internal Calendar object. After calling parse() you have to access the timezone either by accessing the DateFormat‘s Calendar or calling DateFormat.getTimeZone(). Unless you want to throw away the original timezone and use local time, do not use the returned Date value from parse(). Instead use the calendar object after parsing. And the same is true for the format method. If you are going to format a date, pass the calendar with the timezone info into the DateFormat object before calling format(). Here is how you can convert one format to another format preserving the original timezone:

B. SimpleDateTime  http://stackoverflow.com/questions/18122608/simpledateformat-parse-loses-timezone

Convert string to date with TimeZone : http://stackoverflow.com/questions/4203718/converting-string-to-date-with-timezone

 

So here is the final solution, if you don’t want to explicitly store with ” GMT” in the string, and want to display in GMT format:

SHARE
Previous articleHacker News
Next articleAndroid 6 permission