I having a hard time wrapping my head around a problem I am having with Calendar.add()
and I need a sanity check.
My integration tests started to fail today on a project I'm working on. I think it has something to do with a method where I calculating a date by subtracting x amount of days.
For some reason when I subtract 1 day from today (Monday 2 January 2017), I get the result 2016-01-01? I would expect 2017-01-01?
I tried with other dates and it seems to work fine, but seems when it the day is a Monday 2nd of any year it subtracts 1 year too much, instead of one day?
Have I misunderstood something basic with subtracting days in certain situations?
...
// fails. Result is 2010-01-01??
SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd");
Calendar now = Calendar.getInstance();
now.set(2011, 0, 2);
now.add(Calendar.DATE, -1);
assertEquals("2011-01-01", format.format(now.getTime()));
...
// fails. Result is 2016-01-01??
SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd");
Calendar now = Calendar.getInstance();
now.set(2017, 0, 2);
now.add(Calendar.DATE, -1);
assertEquals("2017-01-01", format.format(now.getTime()));
...
// works fine.
SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd");
Calendar now = Calendar.getInstance();
now.set(2017, 0, 5);
now.add(Calendar.DATE, -1);
assertEquals("2017-01-04", format.format(now.getTime()));
...
// works fine.
SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd");
Calendar now = Calendar.getInstance();
now.set(2016, 0, 2);
now.add(Calendar.DATE, -1);
assertEquals("2015-01-01", format.format(now.getTime()));
...