import java.util.Locale;
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.time.DayOfWeek;
import static java.time.temporal.TemporalAdjusters.previousOrSame;
import static java.time.temporal.TemporalAdjusters.nextOrSame;
public class Main {
/**
* Determines first and last day of previous, current or following week from
* provided date according to the provided locale.<br/>
* <br/>
* <strong>NOTE</strong>: Although international standard ISO 8601 defines Monday as a first
* day of the week, several countries, including the United States, Canada,
* and Australia consider Sunday as the start of the week, and several other
* countries starts the week from Saturday.
*
* @param fromDate from which date the week offset should be calculated
* @param weekOffset offset in whole weeks, negative - previous, 0 - current, positive - following weeks
* @param locale locale defining which day should be considered a first day of week
* @return array of length 2, containing the dates of the first and last day of the week
*/
private static LocalDate[] getLocalizedWeekBoundary(LocalDate fromDate, long weekOffset, Locale locale) {
LocalDate[] result = new LocalDate[]{null,null};
DayOfWeek localizedFirstDayOfWeek = WeekFields.of(locale).getFirstDayOfWeek();
DayOfWeek localizedLastDayOfWeek = localizedFirstDayOfWeek.plus(6L);
try{
LocalDate shiftedWeekDate = fromDate.plusWeeks(weekOffset);
result[0] = shiftedWeekDate.with(previousOrSame(localizedFirstDayOfWeek));
result[1] = shiftedWeekDate.with(nextOrSame(localizedLastDayOfWeek));
} catch (Exception ex){
// Just add a bit more explanation for the possible RuntimeException,
// which may be thrown if the provided fromDate/weekOffset combination
// cannot be calculated.
throw new IllegalArgumentException(String.format("Shift of provided date by %d week(s) not supported!", weekOffset), ex);
}
return result;
}
public static void main(String[] args) {
for(Locale locale : Locale.getAvailableLocales()){
if(! locale.getDisplayCountry().isEmpty()){
doTest(locale);
}
}
}
private static void doTest(Locale locale){
LocalDate[] boundary;
String separator = Locale.getDefault().equals(locale) ?
"= = = = = = = = = D E F A U L T = = = = = = = ="
: "- - - - - - - - - - - - - - - - - - - - - - - -";
System.out.printf("%n%s%nIn: %s (%s)%nfirst day of week is: %s%n", separator,
locale.getDisplayCountry(), locale, WeekFields.of(locale).getFirstDayOfWeek());
LocalDate fromDate = LocalDate.now();
for (int shift = -1; shift < 2; shift++) {
boundary = getLocalizedWeekBoundary(fromDate, shift, locale);
System.out.printf("Shift %+2d => first: %s - last: %s%n", shift, boundary[0], boundary[1]);
}
}
}
Чтоб предупредить вопрос, зачем нужны такие подскоки:
Веселые картинки