一、代码
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.TemporalAdjusters;
/**
* @author Alan Chen
* @description LocalDateTime工具类
* JDK 1.8以上
* 一般用于报表统计:日统计、周统计、月统计
* @date 2024-01-02
*/
public class LocalDateTimeTool {
/**
* 今天开始时间
*
* @return
*/
public static LocalDateTime startOfTodayTime() {
LocalDateTime now = LocalDateTime.now();
LocalDateTime todayStart = now.with(LocalTime.MIN);
return todayStart;
}
/**
* 今天结束时间
*
* @return
*/
public static LocalDateTime endOfTodayTime() {
LocalDateTime now = LocalDateTime.now();
LocalDateTime todayEnd = now.with(LocalTime.MAX);
return todayEnd;
}
/**
* 本周开始时间
*
* @return
*/
public static LocalDateTime startOfWeekTime() {
LocalDate today = LocalDate.now();
LocalDate startOfWeek = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
LocalDateTime startOfWeekDateTime = LocalDateTime.of(startOfWeek, LocalTime.MIN);
return startOfWeekDateTime;
}
/**
* 本周结束时间
*
* @return
*/
public static LocalDateTime endOfWeekTime() {
LocalDate today = LocalDate.now();
LocalDate endOfWeek = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
LocalDateTime endOfWeekDateTime = LocalDateTime.of(endOfWeek, LocalTime.MAX);
return endOfWeekDateTime;
}
/**
* 本月开始时间
*
* @return
*/
public static LocalDateTime startOfMonthTime() {
LocalDateTime now = LocalDateTime.now();
LocalDateTime startOfMonth = now.with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN);
return startOfMonth;
}
/**
* 本月结束时间
*
* @return
*/
public static LocalDateTime endOfMonthTime() {
LocalDateTime now = LocalDateTime.now();
LocalDateTime endOfMonth = now.with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MAX);
return endOfMonth;
}
/**
* 获取amount天前的开始时间
*
* @return
*/
public static LocalDateTime startOfTime(int amount) {
LocalDate localDate = LocalDate.now();
LocalDate beforeDay = localDate.plusDays(-amount);
LocalDateTime beforeDayTime = LocalDateTime.of(beforeDay, LocalTime.MIN);//当天00:00:00
return beforeDayTime;
}
/**
* 获取前amount天前的结束时间
*
* @return
*/
public static LocalDateTime endOfTime(int amount) {
LocalDate localDate = LocalDate.now();
LocalDate beforeDay = localDate.plusDays(-amount);
LocalDateTime beforeDayTime = LocalDateTime.of(beforeDay, LocalTime.MAX);//当天23:59:59
return beforeDayTime;
}
}
网友评论