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:
2009-03-10 19:58:06
2009-03-10 19:58:06
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?
Thanks.
Solved! Go to Solution.
03-10-2009 08:57 PM
In the API documentation for SimpleDateFormat, it says the following:
"public class SimpleDateFormat
extends DateFormat
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:
System.out.println(calendar.get(Calendar.HOUR_OF_
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
extends Format
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
System.out.println(formattedDate);
See this thread: http://supportforums.blackberry.com/rim/board/mess
03-12-2009 11:20 AM
11-05-2011 06:43 AM
Hi
can you please help me that how can I get the time in hh:mm style without dates and other strings..
Thanks in Advance
11-05-2011 06:55 AM
01-16-2012 02:54 AM
hi.. I need just the time HH:MM
S format.. how can i get it?
01-16-2012 08:12 AM
The solution was provided above.
Please refrain from posting in "solved" threads.