Question

I'm running into a problem when I construct a DateTime (or LocalDate). I'm converting old code to use joda internally to make things more sane. However I'm running into the +1900 issue...

This passes:

assertEquals(2082, new Date(2082, 1, 1).getYear());

These both fail:

assertEquals(2083, new LocalDate(new Date(2083, 1, 1)).getYear());
assertEquals(2084, new DateTime(new Date(2084, 1, 1)).toLocalDateTime().getYear());

What's going on here? How do I get a DateTime from a Date object?

Was it helpful?

Solution

From javadoc for java.util.Date(int year, int month, int date):

Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).

Allocates a Date object and initializes it so that it represents midnight, local time, at the beginning of the day specified by the year, month, and date arguments.

Parameters: year the year minus 1900. month the month between 0-11. date the day of the month between 1-31.

Besides the fact that it states that the years argument is an offset from the year 1900, you should not be using this constructor as it's deprecated. Instead, use java.util.Calendar:

Calendar cal = Calendar.getInstance();
cal.set(2083, 1, 1);
assertEquals(2083, new LocalDate(cal).getYear());

OTHER TIPS

Your code is fine.

You get confusing results because constructor of Date and its getYear() method work with 1900-based years, that's why they are deprecated.

Also note that conversion from Date to LocalDate / LocalDateTime requires a timezone and uses the default one if none is given explicitly.

a couple of ideas:

    Date date= new Date(2083, 1, 1);

    DateTime dt = new DateTime(2083, 1, 1, 0, 0, 0, 0); 

    assertEquals(2083, new LocalDate(dt).getYear());

    assertEquals(3983, new LocalDate(date).getYear());

Ok. A short introduction: LocalDate is an immutable datetime class representing a date without a time zone. (compare API, http://joda-time.sourceforge.net/apidocs/org/joda/time/LocalDate.html) Calculations on LocalDate are performed using a Chronology. This chronology will be set internally to be in the UTC time zone for all calculations. If you look at the DateTime object, which is basically the same except the fact, that it calculates its fields with respect to a time zone. Calculations are done using the default Chronology (ISOChronology) which is compatible with the modern Gregorian calendar.

Your Problem: java.util.Date constructor uses year, month, day with year being integer y - 1900. In your example 2083 represents the year 3983 (!) (http://docs.oracle.com/javase/7/docs/api/java/util/Date.html). That's it ... you were missing the -1900 .. and yes, java.util.Date has a 1900 problem ;)

-Markus

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top