Strange ww behavior of SimpleDateFormat

Can someone explain why I get these values ​​when trying to parse a date? I tried three different inputs:

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

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

What outputs: 52.2012 (which is suitable for me, since the first week of 2013 is also the last 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)); 

What outputs: 1.2012 (which does absolutely nothing for me)

Does anyone know why this is happening? I need to parse the date in the format (week of the year). (Year). Am I using the wrong template?

+7
java parsing simpledateformat
source share
2 answers

You use ww , which is the "week of the week year", but then yyyy , which is the "calendar year" and not the "weekly year". Setting the week of the week, and then setting the calendar year is a recipe for problems, because these are just separate numbering systems.

You should use yyyy in your format string to indicate the weekly year ... although, unfortunately, it doesn't seem like you can then get the value in a reasonable way. (I would expect the Calendar.WEEKYEAR constant, but there is no such thing.)

In addition, the values ​​of the weekly period begin with 1, not 0 ... and the week does not pass in two weeks; this is either the first week of 2013 or the last week of 2012 ... these are not both.

I would personally avoid using weeks and weeks, if possible - they can be very confusing, especially if the date in one calendar year is in another weekly year.

+16
source share

Use Calendar.getWeekYear () to get the year value synchronized with the Calendar.WEEK_OF_YEAR field. More information about Week of Year and Week Year in the GregorianCalendar document.

+2
source share

All Articles