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
  • 11,551
  • 28
  • 75
  • 141
  • 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
  • 91,013
  • 29
  • 181
  • 233
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,543
  • 4
  • 27
  • 30
0

It should be

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

MosesA
  • 915
  • 5
  • 27
  • 51