2

I'm passing "Jan", "Feb" etc... as integers to the database I need to be passing 1-12 for the corresponding months, but I'm getting 0-11 from Calendar

This is how Im doing it, please help me tweak this to get the months as 1-12 instead as 0-11

//Get month as an integer.
Date date = new SimpleDateFormat("MMM", Locale.ENGLISH).parse(stringMonth);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
System.out.println("month ==" + month);
keyser
  • 18,829
  • 16
  • 59
  • 101
Doc Holiday
  • 9,928
  • 32
  • 98
  • 151

3 Answers3

9
  int month = cal.get(Calendar.MONTH) + 1;

Calendar's month is 0-indexed (Jan = 0). As odd as the above code seems, it is commonly seen in Java because of the rather odd indexing of months in Calendar.

This post has a discussion of this topic: Why is January month 0 in Java Calendar

Community
  • 1
  • 1
John B
  • 32,493
  • 6
  • 77
  • 98
1

That's because Calendar class uses the Month indices from [0-11]

So, to get the indices from [1-12], you can add 1 to the index obtained: -

int month = cal.get(Calendar.MONTH) + 1;
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

Either change:

int month = cal.get(Calendar.MONTH) + 1;

or

System.out.println("month ==" + (month) + 1) ;

(but don't do them both!)

This adds an "offset" of 1 to your month's represented by int, thus shifting it from 0-11 to 1-12 =)

sampson-chen
  • 45,805
  • 12
  • 84
  • 81