Задать вопрос
@Romario21

Как получить дату начала и конца предыдущей недели?

Как узнать дату начала и конца предыдущей недели?
  • Вопрос задан
  • 1058 просмотров
Подписаться 1 Простой Комментировать
Решения вопроса 3
sergey-gornostaev
@sergey-gornostaev Куратор тега Java
Седой и строгий
LocalDate now = LocalDate.now();
LocalDate lastWeekStart = now.minusWeeks(1).with(DayOfWeek.MONDAY);
LocalDate lastWeekEnd = lastWeekStart.plusDays(6);
Ответ написан
Комментировать
leahch
@leahch
3D специалист. Dолго, Dорого, Dерьмово.
Вроде бы jodatime уже давно в яве сидит (!) - joda-time.sourceforge.net/userguide.html#Manipulat...
DateTime dt = new DateTime(); // current
DateTime odt = dt.minusDays(7); // past week
		
DateTime mon = odt.dayOfWeek().setCopy(DateTimeConstants.MONDAY); // get monday of week
DateTime fri = odt.dayOfWeek().setCopy(DateTimeConstants.FRIDAY); // get friday of week
		
System.out.println(mon);
System.out.println(fri);

System.out.println(mon.getDayOfMonth());
System.out.println(fri.getDayOfMonth());


2018-05-14T14:41:06.072+03:00
2018-05-18T14:41:06.072+03:00
14
18
Ответ написан
Комментировать
pi314
@pi314
Президент Солнечной системы и окрестностей
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]);
        }
    }
    
}


Чтоб предупредить вопрос, зачем нужны такие подскоки: Веселые картинки
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы