Re: capturing timezone when parsing java.util.Date
In article <4a453bfb$1@news.spacesst.com>,
Robert Dodier <robert.dodier@gmail.com> wrote:
When a string like "2009-06-26 14:13:00-0400" is parsed to a
java.util.Date via java.text.SimpleDateFormat, the timezone in the
string is lost --- the timezone of the result isn't UTC-04:00,
instead it's the default timezone (or date formatter's timezone, if
it was assigned a non-default value).
When the string "2009-06-26 14:13:00-0400" is parsed, the resulting Date
doesn't have a Timezone; it is merely the number of milliseconds since
the epoch, UT. It can be formatted to show the same Date seen on a clock
in any Timezone:
<console>
2009-06-26 14:13:00GMT-04:00 GMT-04:00 1246039980000
2009-06-26 14:13:00EDT US/Eastern 1246039980000
2009-06-26 19:13:00BST Europe/London 1246039980000
2009-06-26 20:13:00CEST Europe/Berlin 1246039980000
</console>
<code>
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class TestSDF {
private static final String s = "yyyy-MM-dd HH:mm:sszz";
private static final DateFormat f = new SimpleDateFormat(s);
public static void main(String[] args) {
try {
String str = "2009-06-26 14:13:00-0400";
Date date = f.parse(str);
print("GMT-04:00", date);
print("US/Eastern", date);
print("Europe/London", date);
print("Europe/Berlin", date);
} catch (ParseException e) {
e.printStackTrace(System.err);
}
}
private static void print(String tz, Date d) {
f.setTimeZone(TimeZone.getTimeZone(tz));
System.out.println(f.format(d)
+ " " + tz
+ " " + d.getTime());
}
}
</code>
[...]
Any advice about how to capture the timezone when parsing
a date would be appreciated.
"You can use the getAvailableIDs method to iterate through all the
supported time zone IDs," or use a CustomID, described here:
<http://java.sun.com/javase/6/docs/api/java/util/TimeZone.html>
--
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>