Reputation: 5645
I'm developing code in the U.K, I'm formatting a date field which is working OK in the U.K, when I deploy the code onto the server in the U.S the year of the date is wrong by one year. This is the code
public static void main(String args[]) {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
String dateStr = sdf.format(1293840000000L);
System.out.println(dateStr);
}
In the U.K locally on a windows machine this code correctly outputs:
2011-01-01T00:00:00Z
On the server in the U.S on a linux box the same code outputs
2010-12-31T18:00:00Z
It must be some kind of time zone issue?
Upvotes: 0
Views: 140
Reputation: 328598
Your pattern ends with a hardcoded 'Z'
which misleadingly makes you think that it is UTC when it is not. If you use the real time zone:
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z");
(no quote around the Z) you will see that the difference is just a timezone offset.
Here is an example that reproduces the problem, which is due to the fact that SimpleDateFormat
uses the default timezone:
Date dt = new Date(1293840000000L);
TimeZone.setDefault(TimeZone.getTimeZone("America/Chicago"));
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z");
String dateStr = sdf.format(dt);
System.out.println(dateStr); //prints 2010-12-31T18:00:00 -0600
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z");
dateStr = sdf.format(dt);
System.out.println(dateStr); //prints 2011-01-01T00:00:00 +0000
Upvotes: 6
Reputation: 17622
The difference is just one day.. or to be precise few hours
from 31st Dec 2010 to 1st Jan 2011. Since UK's time is ahead of US
A time in milliseconds like 1293840000000L
represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT. So, the same value for UK and US differs.
Upvotes: 3
Reputation: 12243
It looks like a time zone difference. The United States is several hours behind the UK (the exact difference depends on where you are, specifically).
In this case, it's a six hour difference. I believe that's CST to GMT, so odds are your user has a different locale set. This means the string is correct. If you want the same string, you need to either change the locale or makes sure you're printing the GMT offset.
For example, DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
Upvotes: 1
Reputation: 32953
The Javadoc page for DateFormat says
The date is represented as a Date object or as the milliseconds since January 1, 1970, 00:00:00 GMT.
emphasis mine. This means that if you want to specify the date as milliseconds (a long), you're responsible for any time zone calculations.
Upvotes: 1