-1

I would like to understand why this happens, and how can i solve this small issue. I would like to be able to get the week number from a java calendar instance after providing the day, the month and the year. if i do:

  Calendar cal=Calendar.getInstance();
       cal.set(Calendar.DAY_OF_MONTH, 11);
       cal.set(Calendar.MONTH,2);
       cal.set(Calendar.YEAR, 2013);

11 Feb 2013 is week 7, but if i invoke, in the above calendar instance:

int weekNumber=cal.get(Calendar.week_of_year)

I get the week number 11. Any idea why? I tried setting the locale but no difference, the problem is that i can only build a calendar out of these three fields, since i'm reading them from a xml file with a parser and they are in format dd-mm-yyyy with no more information that that

JBoy
  • 5,398
  • 13
  • 61
  • 101
  • For some background and deeper undertanding as to why and alternatives also read this post: http://stackoverflow.com/questions/344380/why-is-january-month-0-in-java-calendar – MickJ Apr 01 '13 at 20:50
  • See http://stackoverflow.com/questions/344380/why-is-january-month-0-in-java-calendar – Aaron Kurtzhals Apr 01 '13 at 20:50

2 Answers2

0

Months fields in Calendar are zero based. The value 2 corresponds to Calendar.MARCH. To avoid confusion, better to use the Calendar constants. You could use:

cal.set(Calendar.MONTH, Calendar.FEBRUARY);
Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

You have used March, because Java months in Calendar are 0-based: 0 = January, 1 = February, 2 = March.

Use

cal.set(Calendar.MONTH,1);

or

cal.set(Calendar.MONTH, Calendar.FEBRUARY);

if you can use a constant. Else, subtract 1 from the month you received from your parser.

rgettman
  • 176,041
  • 30
  • 275
  • 357