I have a system where I through a third party lib gets a date. I know for a fact that the date entered is 1914-08-28 and I don't care for the hours and minutes. I need to deliver this date to the client and it should be formatted like 1914-08-28T00:00.
What I get from the third party lib is a java.util.Date and while debugging I stumpled upon something that to me looked strange.
Take a look at the following image. I have a date that when calling toString()
it returns Thu Aug 27 22:00:00 CET 1914, but when you look at the contained cdate
it looks like being in Zulu time.
Formatting this with the DateFormat gives me 1914-08-27T00:00:
java.text.DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'00:00");
What I really expected here is that I have a date in Zulu time (1914-08-27T22:00Z) which is equivalent to 1914-08-28T00:00 CET (the following day).
This can be reproduced with the following code.
Calendar instance.set(1914, 7, 28, 22, 0);
instance.setTimeZone(TimeZone.getTimeZone("CET"));
Date d = instance.getTime();
Now d
will display CET time and the cdate (visible debugging) will show Zulu time, but they are not different. If the default time zone is used I would expect the CET time to be different than the Zulu time.
What is the explanation for this?
A java.util.Date
isn't in any particular time zone - it's just an instant in time, which will have different local times around the world.
Internally, it's a number of milliseconds since the Unix epoch, but frankly it could be a different representation... and although we usually think of "the Unix epoch" as 1970-01-01T00:00:00Z, you can equally think of it as 1970-01-01T01:00:00+01:00... they represent the same point in time.
Fundamentally, stop thinking about java.util.Date
as being in any time zone - it's not, and toString()
always just uses the system default time zone, to the confusion of many developers. Always use a dedicated formatter (e.g. SimpleDateFormat
) and specify the time zone you're interested in.
Oh, and ideally move to using java.time
or Joda Time, both of which are far superior date/time APIs...
See more on this question at Stackoverflow