How to get the range time of the week where any date is located?

Table of contents

1. Detailed explanation

Main logic:

2. The definition of the method in the tool class


1. Detailed explanation

// 获取当前日期
LocalDate now = LocalDate.now(); 

// 获取本周第一天
LocalDate firstDayOfWeek = now.minusDays(now.getDayOfWeek().getValue() - 1);

// 获取本周第一天的00:00时间
LocalDateTime weekStartDate = firstDayOfWeek.atStartOfDay();

// 获取本周最后一天 
LocalDate lastDayOfWeek = now.plusDays(7 - now.getDayOfWeek().getValue());  

// 获取本周最后一天的23:59:59时间
LocalDateTime weekEndDate = LocalDateTime.of(lastDayOfWeek, LocalTime.MAX);

// 输出
System.out.println("weekStartDate: " + weekStartDate); 
System.out.println("weekEndDate: " + weekEndDate);

Main logic:

1. Get the current date now
2. Subtract the current weekday value minusDays(now.getDayOfWeek().getValue() - 1) from now to get the first day of the week
3. Add 7 days to the first day and subtract The current weekday value plusDays(7 - now.getDayOfWeek().getValue()) to get the last day of the week
4. Combine time to get the start and end time of the week


2. Definition of method

     /**
     * 1. now.getDayOfWeek().getValue() 获取now这一天是这一周的第几天,会返回1-7。
     * 2. now.minusDays(now.getDayOfWeek().getValue() - 1) 获取now这一周的第一天。
     * 3. atStartOfDay() 获取那一天的00:00:00时间。
     * @param now
     * @return
     */
    public static LocalDateTime getWeekBeginTime(LocalDate now) {
        return now.minusDays(now.getDayOfWeek().getValue() - 1).atStartOfDay();
    }

    /**
     * 1. now.getDayOfWeek().getValue() 同上,获取这一周的第几天。
     * 2. 8 - now.getDayOfWeek().getValue() 计算出这一周的最后一天离now还有几天。
     * 3. now.plusDays(8 - now.getDayOfWeek().getValue()) 获取这一周的最后一天。
     * 4. LocalTime.MAX 获取23:59:59时间。
     * @param now
     * @return
     */
    public static LocalDateTime getWeekEndTime(LocalDate now) {
        return LocalDateTime.of(now.plusDays(8 - now.getDayOfWeek().getValue()), LocalTime.MAX);
    }

In this way, it is convenient to obtain the range time of the week in which the date of any day is located.

Guess you like

Origin blog.csdn.net/Microhoo_/article/details/132597870