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 :85475520096开发者_C百科4
Shouldn't they be the same number?
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.
Two reasons:
Joda has one based months. So you need to change that.
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.
Zero-based vs. one-based notations
I'm going to guess here that 1997, 01,01
for Joda means January 1st, 1997.
But in Java Calendar, months are numbered from 0 - 11, so 1997,01,01 for Java is actually February 1st.
A better approach is to use --
cal.set(1997, Calendar.JANUARY, 01, 00,00,00);
You should also reset the MILLISECONDS of the Calendar object to 0 as @Amir pointed out.
精彩评论