Can anyone explain why do I get those values while trying to parse a date? I've tried three different inputs, as follows:
1) Third week of 2013
Date date = new SimpleDateFormat("ww.yyyy").parse("02.2013");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(cal.get(Calendar.WEEK_OF_YEAR) + "." + cal.get(Calendar.YEAR));
Which outputs: 02.2013
(as I expected)
2) First week of 2013
Date date = new SimpleDateFormat("ww.yyyy").parse("00.2013");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(cal.get(Calendar.WEEK_OF_YEAR) + "." + cal.get(Calendar.YEAR));
Which outputs: 52.2012
(which is fine for me, since the first week of 2013 is also the last one of 2012)
3) Second week of 2013
Date date = new SimpleDateFormat("ww.yyyy").parse("01.2013");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(cal.get(Calendar.WEEK_OF_YEAR) + "." + cal.get(Calendar.YEAR));
Which outputs: 1.2012
(which makes absolutely no sense to me)
Does anyone know why this happens?? I need to parse a date in the format (week of year).(year). Am I using the wrong pattern?
You're using ww
, which is "week of week-year", but then yyyy
which is "calendar year" rather than "week year". Setting the week-of-week-year and then setting the calendar year is a recipe for problems, because they're just separate numbering systems, effectively.
You should be using YYYY
in your format string to specify the week-year... although unfortunately it looks like you can't then get the value in a sane way. (I'd expect a Calendar.WEEKYEAR
constant, but there is no such thing.)
Also, week-of-year values start at 1, not 0... and no week is in two week-years; it's either the first week of 2013 or it's the last week of 2012... it's not both.
I would personally avoid using week-years and weeks if you possibly can - they can be very confusing, particularly when a date in one calendar year is in a different week year.
Use Calendar.getWeekYear() to get year value synced with Calendar.WEEK_OF_YEAR
field.
There is more information about Week of Year and Week Year at the GregorianCalendar doc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With