1、獲取本月的第一天和最后一天
// 本月第一天
DateTime firstDay = DateUtil.beginOfMonth(new Date());
// 本月最后一條
Date lastDay = DateUtil.endOfMonth(new Date());
2、獲取今天的時間范圍
DateTime beginOfDay = DateUtil.beginOfDay(new Date()); // 2023-09-25 00:00:00
DateTime endOfDay = DateUtil.endOfDay(new Date()); // 2023-09-25 23:59:59
3、獲取本周的第一天和最后一天
DateTime beginOfWeek = DateUtil.beginOfWeek(new Date());
Date endOfWeek=DateUtil.endOfWeek(new Date());
4、獲取上個月的時間范圍
LocalDate currentDate = LocalDate.now(); // 當(dāng)前日期
LocalDate previousMonthDate = currentDate.minusMonths(1); // 上個月日期
Month previousMonth = previousMonthDate.getMonth(); // 上個月的月份
int previousMonthYear = previousMonthDate.getYear(); // 上個月的年份
boolean leapYear = false;
// 判斷是否為閏年
if(previousMonthYear%4 == 0 && previousMonthYear%100 !=0 || previousMonthYear%400 == 0){
leapYear = true;
}
// 上個月的開始時間
LocalDateTime startOfPrevious = LocalDateTime.of(previousMonthYear, previousMonth, 1, 0, 0, 0);
// 上個月的結(jié)束時間
LocalDateTime endOfPrevious = LocalDateTime.of(previousMonthYear, previousMonth, previousMonth.length(leapYear), 23, 59, 59);
// 將LocalDateTime 轉(zhuǎn)換為Date類型
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime startMonth = startOfPrevious.atZone(zoneId);
ZonedDateTime endMonth = endOfPrevious.atZone(zoneId);
Date beginOfPreviousMonth = Date.from(startMonth.toInstant());
Date endOfPreviousMonth = Date.from(endMonth.toInstant());
5、獲取本季度的第一天和最后一天
DateTime beginOfQuarter = DateUtil.beginOfQuarter(new Date());
DateTime endOfQuarter = DateUtil.endOfQuarter(new Date());
6、獲取今年的第一天和最后一天文章來源:http://www.zghlxwxcb.cn/news/detail-784839.html
DateTime beginOfYear = DateUtil.beginOfYear(new Date());
DateTime endOfYear = DateUtil.endOfYear(new Date());
7、獲取上一年的第一天和最后一天文章來源地址http://www.zghlxwxcb.cn/news/detail-784839.html
Year currentYear = Year.now(); // 當(dāng)前年份
Year previousYear = currentYear.minusYears(1); // 上一年
// 上一年的開始時間
LocalDateTime previousYearStart = previousYear.atDay(1).atStartOfDay();
// 上一年的結(jié)束時間
LocalDateTime previousYearEnd = previousYear.atMonth(12).atEndOfMonth().atTime(23, 59, 59);
// 將LocalDateTime 轉(zhuǎn)換為Date類型
ZoneId zoneYearId = ZoneId.systemDefault();
ZonedDateTime zdt = previousYearStart.atZone(zoneYearId);
ZonedDateTime end = previousYearEnd.atZone(zoneYearId);
Date beginOfPreviousYear = Date.from(zdt.toInstant());
Date endOfPreviousYear = Date.from(end.toInstant());
到了這里,關(guān)于Java獲取今天、本周、本月、本季度、上月、上一年的時間范圍的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!