title: SimpleDateFormat Week Calculations
body: <p>I'm getting some puzzling results with SimpleDateFormat and am hoping that someone can shed some light on the issue. The output:</p>
  
  <pre><code>Time          = Mon Dec 27 00:00:00 PST 2010
  2010-01 &lt;--- THIS IS WHAT I DON'T UNDERSTAND
  Start of week = Sun Dec 26 00:00:00 PST 2010
  2010-01
  End of Week   = Sat Jan 01 23:59:59 PST 2011
  2011-01
  </code></pre>
  
  <p>Should I be treating the last "week" of the year that extends to the next year as a special case? Or is this the correct way to interpret this? Obviously when attempting to organize week sequentially, the order is incorrect. Adjusting the initial values, Dec 25, 2005 is considered the 53rd week. I haven't looked at Joda yet to see if Joda produces similar results.</p>
  
  <p>The relevant code:</p>
  
  <pre><code>private static Date getStartOfWeek( Date d ) {
    Calendar calendar = Calendar.getInstance();
    calendar.clear();
    calendar.setTime( d );
  
    calendar.set( Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek() );
  
    return calendar.getTime();  
  }
  
  private static Date getEndOfWeek( Date d ) {
    Calendar calendar = Calendar.getInstance();
    calendar.clear();
  
    calendar.setTime( d );
    calendar.add( Calendar.WEEK_OF_YEAR, 1 );
    calendar.set( Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek() );
    calendar.add( Calendar.MILLISECOND, -1 );
  
    return calendar.getTime();
  }
  
  
  Calendar calendar = Calendar.getInstance();
  calendar.clear();
  calendar.set( 2010, Calendar.DECEMBER, 27 );
  Date d = calendar.getTime();
  Date start = getStartOfWeek( d );
  Date end = getEndOfWeek( d );
  SimpleDateFormat fmt = new SimpleDateFormat( "yyyy-ww" );
  
  System.out.println( "Time          = " + d );
  System.out.println( fmt.format( d ) );
  System.out.println( "Start of week = " + start );
  System.out.println( fmt.format( start ) );
  System.out.println( "End of Week   = " + end );
  System.out.println( fmt.format( end ) );
  </code></pre>
  
  <p>Background: I found this when using the crosstab (date grouped into week) in JasperReports.</p>
  
  <p>EDIT: I am using JDK 1.6.0_25</p>
  
  <p>EDIT: It seems that I will have to use Joda to get the correct result. TO get the week start/end, I ended up using: <code>LocalDate.withDayOfWeek</code>. To retrieve the year and week number, I used <code>DateTime.getWeekyear</code> and <code>DateTime.getWeekOfWeekyear</code>.</p>