Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behaviour of ww SimpleDateFormat

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?

like image 718
fvdalcin Avatar asked May 08 '14 12:05

fvdalcin


Video Answer


2 Answers

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.

like image 163
Jon Skeet Avatar answered Sep 24 '22 03:09

Jon Skeet


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.

like image 31
endragor Avatar answered Sep 24 '22 03:09

endragor