Why does setting date with calendar give me the wrong date

前端 未结 3 1458
长发绾君心
长发绾君心 2021-01-24 07:20

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(         


        
相关标签:
3条回答
  • 2021-01-24 07:31

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

    0 讨论(0)
  • 2021-01-24 07:42

    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);
    
    0 讨论(0)
  • 2021-01-24 07:46

    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.

    0 讨论(0)
提交回复
热议问题