javacalendarjodatime

Calendar.getTime() return different Date objects


I have some code witch Converts Joda- DateTime to java.util.Date using Calendar.

 Calendar cal = Calendar.getInstance(zone.toTimeZone());
 DateTime zonedDT = internal.toDateTime(zone);
 // Due to JDK and Joda-Time both have time zone implementations and these differ in accuracy.
 // Joda-Time's implementation is generally more up to date and thus more accurate - for example JDK1.3 has no historical data.
 // The effect of this is that the field values of the Calendar may differ from those of this object, even though the millisecond value is the same.
 // Most of the time this just means that the JDK field values are wrong, as our time zone information is more up to date
 // That's why we should manually set date,year, time to calendar
 cal.set(zonedDT.getYear(), zonedDT.getMonthOfYear() - 1, zonedDT.getDayOfMonth(), zonedDT.getHourOfDay(), zonedDT.getMinuteOfHour(), zonedDT.getSecondOfMinute());
 return cal.getTime();

The problem is that there is a difference between Date instances created in such way in milliseconds.

I have tryed in Intellij Idea using code framgent evaluation this code

Calendar cal = Calendar.getInstance();
cal.set(2014,3,18,14,44,32);
cal.getTime()

and it returns different Date. Difference is in milliseconds.
My OS is Windwos.
jdk 1.7.0_25


Solution

  • Adding a line as below:

    cal.set(Calendar.MILLISECOND, 0);
    

    Will set the milliseconds value. The API docs specify the field as below:

    public final void set(int year, int month, int date, int hourOfDay, int minute, int second)
    

    So it doesn't offer the granularity to set the millisconds.

    Side note:

    If your using the Java Date libs checkout Jodatime: http://www.joda.org/joda-time/ its a lot better!