Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joda time's DateTime converted to java.util.Date strange issue

Tags:

java

jodatime

I ran into a strange issue. Here is a snippet of code that describes it:

DateTimeZone dtz = DateTimeZone.forOffsetHours(0);

DateTime dt = new DateTime(dtz);

System.out.println(dt);
System.out.println(dt.toDate());

the output is:

2012-02-29T17:24:39.055Z
Wed Feb 29 19:24:39 EET 2012

I'm located UTC+2, but this action is supposed to create a java.util.Date object which is initialized for UTC time. What am I missing?

like image 501
Martin Asenov Avatar asked Feb 29 '12 17:02

Martin Asenov


2 Answers

Date doesn't know about a time zone at all - it only represents an instant in time (like Joda Time's Instant type). It's just a number of milliseconds since the Unix epoch. When you call Date.toString(), it always uses the system local time zone for converting that into a readable text form.

So there's nothing wrong here - just an expectations failure over either the meaning of java.util.Date or its toString() behaviour, or both.

(As an aside, prefer DateTimeZone.UTC over creating your own.)

like image 130
Jon Skeet Avatar answered Nov 15 '22 20:11

Jon Skeet


To get a JDK Date that matches Joda's DateTimeconvert to LocalDateTimefirst.

As explained in the other answers, the time in milliseconds does not change depending on the timezone:

DateTime local = DateTime.now()
Date localJDK = local.toDate()
assert localJDK.getTime() == local.toInstant().getMillis()

DateTime differentTimeZone = DateTime.now(DateTimeZone.forID('America/Chicago'))
Date localJDK2 = differentTimeZone.toDate()
assert differentTimeZone.toInstant().getMillis() == localJDK2.getTime()
assert localJDK.getTime() == localJDK2.getTime()

Converting a LocalDateTime to Date will change that:

Date differentTimeZoneJDK = differentTimeZone.toLocalDateTime().toDate()
assert localJDK.getTime() != differentTimeZoneJDK.getTime()
like image 20
Mathias Avatar answered Nov 15 '22 19:11

Mathias