0
Date fakeDate = sdf.parse("15/07/2013 11:00 AM");
Calendar calendar = Calendar.getInstance()
calendar.setTime(fakeDate);
int currentMonth = calendar.get(Calendar.MONTH);

I get currentMonth == 6 instead of 7.

why is that?

Elad Benda2
  • 13,852
  • 29
  • 82
  • 157
  • 1
    While the question has been answered, the good solution is to drop the outdated `Calendar` class and use [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/), instead. It is so much nicer to work with, and it numbers months the same way humans do. – Ole V.V. Mar 11 '18 at 06:59

3 Answers3

5

Because Calendar.MONTH is ZERO based. Why?

Check the docs: (always)

Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

Community
  • 1
  • 1
Maroun
  • 94,125
  • 30
  • 188
  • 241
2

As the doc says - Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

So try something like this

int currentMonth = calendar.get(Calendar.MONTH)+1;

Because calendar.get(Calendar.MONTH) shall give you (currentMonthValue-1) as the value of january starts with 0

SparkOn
  • 8,806
  • 4
  • 29
  • 34
0

It should be

int currentMonth = calendar.get(Calendar.MONTH)+1;

MosesA
  • 925
  • 5
  • 27
  • 53