Johann
Johann

Reputation: 29885

Why does setting date with calendar give me the wrong date

I am setting the date to 2013-01-01 00:00:00, but the date comes out as Fri Feb 01 00:00:00 GMT+01:00 2013

Why?

Calendar calendar = Calendar.getInstance();
calendar.set(2013, 1, 1, 0, 0, 0);
Date startDate = calendar.getTime();

Upvotes: 1

Views: 1455

Answers (3)

AForsberg
AForsberg

Reputation: 1194

Just a gotcha that's related...

At first I thought this wasn't the same problem I was getting, because my year was wrong. I had set '12' for December, but because months are an offset and start at 0, Calendar will actually roll that 12 over to mean January of the next year, so if your year is wrong, check if your month is also wrong, it could be rolling over like mine did.

i.e. setDate(2015, 12, 6) results in a Date of January 6th, 2016

So USE THE CALENDAR MONTH CONSTANTS.

Upvotes: 0

Bill the Lizard
Bill the Lizard

Reputation: 406125

Month numbering starts at 0 in Java's date classes. Use the month constants in the Calendar class to avoid this common mistake.

calendar.set(2013, Calendar.JANUARY, 1, 0, 0, 0);

Upvotes: 7

Adam Sznajder
Adam Sznajder

Reputation: 9216

1 means Feburary. 0 is January. Months are indexed starting from 0. It's always better to use mnemonics: Calendar.JANUARY

Upvotes: 7

Related Questions