[SalesForce] How to get correct week number in Apex

I am struggling to get the correct week in year for any given date.

Datetime dt = Datetime.newInstanceGmt(2014, 1, 5).addHours(12);
Integer week = Integer.valueOf(dt.formatGmt('w'));
System.debug('Locale: ' + UserInfo.getLocale());
System.debug('week number of ' + dt + ' is ' + week);
System.debug('first day of week is: ' + dt.dateGmt().toStartOfWeek());

January 5th this year was a Sunday, so I would expect it to return week number 1 for a European Locale such as 'de-DE' and week number 2 for a US Locale.

EDIT: I added another line to the script above. This last line shows me that the first day of the week containing the 5th of January 2014 is actually the previous Monday (30th December 2013). Which is correct for the Locale 'de-DE'! But the first Sunday of the year is in week 2? Looks really like a bug to me.

Unfortunately it returns tells me that the day is in week 2 for both Locales.

Is this a bug?

Best Answer

This has more to do with the ISO 8601 Date format than Salesforce. A week in a year starts on the first thursday in the calendar.

ISO 8601 Week Dates

If 1 January is on a Monday, Tuesday, Wednesday or Thursday, it is in week 01. If 1 January is on a Friday, Saturday or Sunday, it is in week 52 or 53 of the previous year (there is no week 00). 28 December is always in the last week of its year.

Edit:

While the above is true, it doesn't apply to you. I see what you are saying now. It seems to work when formatting this way:

DateTime.newInstanceGmt(Date.newInstance(2014, 1, 5).toStartOfWeek(), Time.NewInstance(12,0,0,0)).format('w')

Related Topic