I would like to format dates, for a specific time zone, GMT, and I want the result of that formatting to be the same always, regardless of which time zone the application runs in.
E.g., create Calendar instance in GMT time zone and populate its fields:
TimeZone gmtTimeZone = TimeZone.getTimeZone( "GMT" );
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone( gmtTimeZone );
calendar.set( Calendar.YEAR, 1982 );
calendar.set( Calendar.MONTH, Calendar.JANUARY );
calendar.set( Calendar.DAY_OF_MONTH, 23 );
calendar.set( Calendar.HOUR, 1 );
calendar.set( Calendar.MINUTE, 2 );
calendar.set( Calendar.SECOND, 3 );
calendar.set( Calendar.MILLISECOND, 4 );
Retrieve UTC timestamp from calendar:
Date utcDate = calendar.getTime();
From what I understand, utcDate is now the number of milliseconds between January 1, 1970, 00:00:00.000 GMT and January 23, 1982, 01:02:03.004 GMT.
See Date Javadocs:
/**
* Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
* represented by this <tt>Date</tt> object.
*
* @return the number of milliseconds since January 1, 1970, 00:00:00 GMT
* represented by this date.
*/
Create date formatter and set its time zone to GMT too:
SimpleDateFormat dateTimeFormat = new SimpleDateFormat( "yyyy-MM-dd' 'HH:mm:ss.SSSZ" );
dateTimeFormat.setTimeZone( gmtTimeZone );
Format date object into string:
String stringDate = dateTimeFormat.format( utcDate );
Now, when I do:
System.out.println( utcDate.getTime() );
System.out.println( stringDate );
I get:
> 380638923004
> 1982-01-23 13:02:03.004+0000
However, what I expected was (note 13 hours vs 01 hours):
> 1982-01-23 01:02:03.004+0000
I.e., because I set the time to 1 (1am) with calendar.set( Calendar.HOUR, 1 );, I expect the time to be 1 (1am) not 13 (1pm).
Where am I going wrong?
calendar.set( Calendar.HOUR, 1 );- Alex Averbuch