| | |
| | | import java.time.LocalDate; |
| | | import java.time.LocalDateTime; |
| | | import java.time.LocalTime; |
| | | import java.time.format.DateTimeFormatter; |
| | | import java.time.temporal.TemporalAdjusters; |
| | | import java.time.temporal.WeekFields; |
| | | import java.util.Locale; |
| | |
| | | |
| | | @Test |
| | | void contextLoads() { |
| | | // 获取当前日期 |
| | | LocalDate today = LocalDate.now(); |
| | | |
| | | // 获取本月的第一天和最后一天 |
| | | LocalDate firstDayOfMonth = today.with(TemporalAdjusters.firstDayOfMonth()); |
| | | LocalDate lastDayOfMonth = today.with(TemporalAdjusters.lastDayOfMonth()); |
| | | DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss"); |
| | | String a = "09:00:00"; |
| | | String b = "17:00:00"; |
| | | LocalTime now = LocalTime.now(); |
| | | LocalTime startTime = LocalTime.parse(a, formatter); |
| | | LocalTime endTime = LocalTime.parse(b, formatter); |
| | | |
| | | // 获取周字段信息(根据区域设置) |
| | | WeekFields weekFields = WeekFields.of(Locale.getDefault()); |
| | | |
| | | // 获取本月第一天的周一 |
| | | LocalDate startOfWeek = firstDayOfMonth.with(TemporalAdjusters.previousOrSame(weekFields.getFirstDayOfWeek())); |
| | | |
| | | // 遍历本月所有天数,找出每周的第一天和最后一天 |
| | | LocalDate endOfWeek; |
| | | while (startOfWeek.isBefore(firstDayOfMonth.plusMonths(1))) { |
| | | endOfWeek = startOfWeek.plusDays(6); |
| | | LocalDateTime startDateTime = LocalDateTime.of(startOfWeek, LocalTime.MIDNIGHT); |
| | | LocalDateTime endDateTime = LocalDateTime.of(endOfWeek, LocalTime.MIDNIGHT); |
| | | |
| | | System.out.println("Week starts on " + startDateTime + " and ends on " + endDateTime); |
| | | |
| | | startOfWeek = startOfWeek.plusWeeks(1); |
| | | } |
| | | // 检查当前时间是否在范围内(包括边界) |
| | | boolean isWithinRange = !now.isBefore(startTime) && !now.isAfter(endTime); |
| | | System.out.println(isWithinRange); |
| | | } |
| | | } |