Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do JodaTime and Calendar return different results

Why does this test fail:

    DateTime dateTime = new DateTime(1997,01,01,00,00,00,00, DateTimeZone.UTC);
    long jodaMills = dateTime.getMillis();

    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    cal.set(1997,01,01,00,00,00);
    long calMills = cal.getTimeInMillis();

    Assert.assertEquals(jodaMills, calMills);

I get a result of: Expected :852076800000 Actual :854755200964

Shouldn't they be the same number?

like image 636
ryber Avatar asked Jul 26 '11 19:07

ryber


2 Answers

Calendar has zero based months, and JodaTime months fields starts at 1.

So, in JodaTime, January is month 1, but in Calendar, January is month 0.

Therefore, in your example you are comparing January 1st to February 1st, hence the difference in values.

There is also a difference in milliseconds, as the JodaTime is being set to zero, but the Calendar object is not.

like image 107
Codemwnci Avatar answered Dec 09 '22 12:12

Codemwnci


Two reasons:

  1. Joda has one based months. So you need to change that.

  2. Calendar is poorly designed. You are not setting the milliseconds of the second to 0. cal.set(MILLISECOND, 0)

Here is the javadoc

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

Which is missing the millisecond field.

like image 43
Amir Raminfar Avatar answered Dec 09 '22 14:12

Amir Raminfar