javaandroiddatecalendar

Error while constructing date


I have such code:

Log.d(TAG, "day=%d, month=%d, year=%s", day, month, year);

Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);

Log.i(TAG, "Date is parsed to %tF", c.getTime(), c.get(Calendar.DAY_OF_MONTH));

And this is log I get when executing:

day=11, month=11, year=1985
Date is parsed to 1985-12-10

Why not 1985-12-11? It works correct for some dates or in debug mode. But why it is not always working?

I also have similar issues when working with Date and when parsing dates from String via SimpleDateFormat

EDIT: Other examples of this code executing:

day=1, month=0, year=2012
Date is parsed to 2012-01-01

day=25, month=11, year=2011
Date is parsed to 2011-12-25

day=4, month=10, year=1979
Date is parsed to 1979-11-03

day=3, month=11, year=1984
Date is parsed to 1984-12-02

day, month and year can't be changed from other threads.


Solution

  • Thanks for the help. It seems to be some Android devices issue. It has appeared in 3 of 5 devices. I have fixed it by specifying time.

    c.set(Calendar.HOUR_OF_DAY, 12);
    c.set(Calendar.MINUTE, 30);