Calendar instance providing wrong week number when calendar built with basic fields [duplicate]

StackOverflow https://stackoverflow.com/questions/15751497

  •  31-03-2022
  •  | 
  •  

Question

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

Was it helpful?

Solution

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);

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top