java8获取本周本月第一天和最后一天的时间戳
时间: 2024-02-18 21:55:59 浏览: 208
可以使用Java 8中的LocalDate类和TemporalAdjusters类来获取本周和本月的第一天和最后一天的时间戳。具体实现方法如下:
1. 获取本周第一天和最后一天的时间戳:
```
LocalDate today = LocalDate.now();
LocalDate firstDayOfWeek = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
LocalDate lastDayOfWeek = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
long firstDayOfWeekTimestamp = firstDayOfWeek.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();
long lastDayOfWeekTimestamp = lastDayOfWeek.atTime(LocalTime.MAX).atZone(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();```
其中,ZoneOffset.ofHours(8)表示东八区,toInstant().toEpochMilli()表示将LocalDate转换为时间戳。
2. 获取本月第一天和最后一天的时间戳:
```
LocalDate today = LocalDate.now();
LocalDate firstDayOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());
LocalDate lastDayOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
long firstDayOfMonthTimestamp = firstDayOfMonth.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();
long lastDayOfMonthTimestamp = lastDayOfMonth.atTime(LocalTime.MAX).atZone(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();
```
其中,firstDayOfMonth()表示获取本月第一天,lastDayOfMonth()表示获取本月最后一天,其他部分与获取本周时间戳相同。
阅读全文