项目中的大屏统计经常会用到根据时间去统计相关数据,所以就需要获取相应的开始时间与结束时间,以便在sql中能查询出对应区间的数据。
代码直接复制就可以用,返回的数据就是开始时间与结束时间。
public String getTime(String dateType) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
if ("1".equals(dateType)) {
//今日
LocalDateTime dayStart = now.with(LocalTime.MIN);
LocalDateTime dayEnd = now.with(LocalTime.MAX);
return dayStart.format(fmt) + "," + dayEnd.format(fmt);
} else if ("2".equals(dateType)) {
//本周
int dayOfWeek = now.getDayOfWeek().getValue();
LocalDateTime weekStart = now.minusDays(dayOfWeek - 1).with(LocalTime.MIN);
LocalDateTime weekEnd = now.plusDays(7 - dayOfWeek).with(LocalTime.MAX);
return weekStart.format(fmt) + "," + weekEnd.format(fmt);
} else if ("3".equals(dateType)) {
//本月
LocalDateTime monthStart = now.with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN);
LocalDateTime monthEnd = now.with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MAX);
return monthStart.format(fmt) + "," + monthEnd.format(fmt);
} else if ("4".equals(dateType)) {
LocalDate date = LocalDate.now();
LocalDate quarterStart = getStartOrEndDayOfQuarter(date, true);
LocalDate quarterEnd = getStartOrEndDayOfQuarter(date, false);
return quarterStart.format(fmt) + "," + quarterEnd.format(fmt);
} else {
//本年
LocalDateTime yearStart = now.with(TemporalAdjusters.firstDayOfYear()).with(LocalTime.MIN);
LocalDateTime yearEnd = now.with(TemporalAdjusters.lastDayOfYear()).with(LocalTime.MAX);
return yearStart.format(fmt) + "," + yearEnd.format(fmt);
}
}
public static LocalDate getStartOrEndDayOfQuarter(LocalDate today, Boolean isFirst) {
LocalDate resDate = LocalDate.now();
if (today == null) {
today = resDate;
}
Month month = today.getMonth();
Month firstMonthOfQuarter = month.firstMonthOfQuarter();
Month endMonthOfQuarter = Month.of(firstMonthOfQuarter.getValue() + 2);
if (isFirst) {
resDate = LocalDate.of(today.getYear(), firstMonthOfQuarter, 1);
} else {
resDate = LocalDate.of(today.getYear(), endMonthOfQuarter, endMonthOfQuarter.length(today.isLeapYear()));
}
return resDate;
}
拿到返回值,将其以逗号分隔开就可以用了(参数的dateType值需要前端传,前端选择相应的时间,比如前端传3,那就是获取当前时间的本月开始时间与结束时间)