javadatecalendarjodatimeweek-number

Why dec 31 2010 returns 1 as week of year?


For instance:

Calendar c = Calendar.getInstance();
DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
c.setTime( sdf.parse("31/12/2010"));
out.println( c.get( Calendar.WEEK_OF_YEAR ) );  

Prints 1

Same happens with Joda time.

:)


Solution

  • The definition of Week of Year is Locale dependent.

    How it is defined in US is discused in the other posts. For example in Germany (DIN 1355-1 / ISO 8601): the first Week* of Year is the first week with 4 or more days in the new year.

    *first day of week is Monday and last day of week is Sunday

    And Java’s Calendar pays attention to the locale. For example:

    public static void main(String[] args) throws ParseException {
    
        DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        Date lastDec2010 = sdf.parse("31/12/2010");
    
        Calendar calUs = Calendar.getInstance(Locale.US);       
        calUs.setTime(lastDec2010);
    
        Calendar calDe = Calendar.getInstance(Locale.GERMAN);       
        calDe.setTime(lastDec2010);
    
        System.out.println( "us: " + calUs.get( Calendar.WEEK_OF_YEAR ) ); 
        System.out.println( "de: " + calDe.get( Calendar.WEEK_OF_YEAR ) );
    }
    

    prints:

    us: 1
    de: 52
    

    ADDED For the US (and I can think of that it is the same for Mexico) the 1. Week of Year is the week where the 1. January belongs to. -- So if 1. Januar is a Saturday, then the Friday before (31. Dec) belongs the same week, and in this case this day belongs to the 1. Week of Year 2011.