03-10-2009 08:01 PM
I've seen countless examples online, but I can't figure out why this isn't working:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String eventDateString; Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); // GMT will always be supported by getTimeZone eventDateString = dateFormat.format(calendar.getTime()); System.out.println(eventDateString); Calendar calendarLocal = Calendar.getInstance(); eventDateString = dateFormat.format(calendarLocal.getTime()); System.out.println(eventDateString);
This results in this output:
I would expect the first one to be 4 hours ahead since the device I'm using is EST.
Am I missing something about how these methods work?
Solved! Go to Solution.
03-10-2009 08:57 PM
In the API documentation for SimpleDateFormat, it says the following:
"public class SimpleDateFormat
Formats and parses dates in a locale-sensitive manner"
Add the following to your code to demonstrate that the hours are in fact different in the Calendar objects:
If you wish to use SimpleDateFormat to provide GMT output, you have to manipulate the time yourself, by adding the appropriate offset.
03-11-2009 04:01 PM
Thanks peter, I never thought it would be a problem with the formatter, since I thought it's only job was to format dates.
So SimpleDateFormat basically ignores the timezone of the Calendar that you give it and uses your local timezone?
Is there no formatter which takes a timezone?
03-11-2009 06:48 PM
"Is there no formatter which takes a timezone?"
Think that DateFormat does, though I have never used it. The java doc says:
public abstract class DateFormat
Defines fundamental functionality for locale-independent formatting of date/time information.
Have a look at it and if you get it to work for you, I'd be interested to see some sample code.
DateFields respect TimeZone too.
03-12-2009 10:47 AM - edited 03-12-2009 11:06 AM
I'm a big **bleep**...
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); //e.g. 2008-06-03T12:15:03Z
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.setTime(new Date(System.currentTimeMillis())); //now
String formattedDate = dateFormat.format(c, new StringBuffer(), null).toString(); //formatted in UTC/GMT time