Start of week for locale using Joda-Time
How do you determine which day of the week is considered the “start” according to a given Locale using Joda-Time?
Point: Most countries use the international standard Monday as first day of week (!). A bunch others use Sunday (notably USA). Others apparently Saturday. Some apparently Wednesday?!
Wikipedia "Seven-day week"#Week_number
Solution 1:
Joda-Time uses the ISO standard Monday to Sunday week.
It does not have the ability to obtain the first day of week, nor to return the day of week index based on any day other than the standard Monday. Finally, weeks are always calculated wrt ISO rules.
Solution 2:
There's no reason you can't make use of the JDK at least to find the "customary start of the week" for the given Locale. The only tricky part is translating constants for weekdays, where both are 1 through 7, but java.util.Calendar is shifted by one, with Calendar.MONDAY = 2 vs. DateTimeConstants.MONDAY = 1.
Anyway, use this function:
/**
* Gets the first day of the week, in the default locale.
*
* @return a value in the range of {@link DateTimeConstants#MONDAY} to
* {@link DateTimeConstants#SUNDAY}.
*/
private static final int getFirstDayOfWeek() {
return ((Calendar.getInstance().getFirstDayOfWeek() + 5) % 7) + 1;
}
Add a Locale to Calendar.getInstance() to get a result for some Locale other than the default.
Solution 3:
Here is how one might work around Joda time to get the U.S. first day of the week:
DateTime getFirstDayOfWeek(DateTime other) {
if(other.dayOfWeek.get == 7)
return other;
else
return other.minusWeeks(1).withDayOfWeek(7);
}
Or in Scala
def getFirstDayOfWeek(other: DateTime) = other.dayOfWeek.get match {
case 7 => other
case _ => other.minusWeeks(1).withDayOfWeek(7)
}