import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;
/**
* jdk8 获取当天,本周,本月,本季度,本年起始时间工具类 LocalDateTime
*/
public class LocalDateTimeUtils {
public static final String MinTime = "T00:00:00";
public static final String MaxTime = "T23:59:59.999999999";
public static String YMD = "yyyy-MM-dd";
public static String YMD_SFM = "yyyy-MM-dd HH:mm:ss";
/**
* 当天的开始/结束时间
* @param today
* @param isFirst true 表示开始时间,false表示结束时间
* @return
*/
public static LocalDateTime getStartOrEndDayOfDay(LocalDate today, Boolean isFirst) {
LocalDate resDate = LocalDate.now();
if (today == null) {
today = resDate;
}
if (isFirst) {
return LocalDateTime.of(today, LocalTime.MIN);
} else {
return LocalDateTime.of(today, LocalTime.MAX);
}
}
/**
* 本周的开始/结束时间
* @param today
* @param isFirst true 表示开始时间,false表示结束时间
* @return
*/
public static LocalDateTime getStartOrEndDayOfWeek(LocalDate today, Boolean isFirst) {
String time = MinTime;
LocalDate resDate = LocalDate.now();
if (today == null) {
today = resDate;
}
DayOfWeek week = today.getDayOfWeek();
int value = week.getValue();
if (isFirst) {
resDate = today.minusDays(value - 1);
} else {
resDate = today.plusDays(7 - value);
time = MaxTime;
}
LocalDateTime localDateTime = LocalDateTime.parse(resDate.toString() + time);
return localDateTime;
}
/**
* 本月的开始/结束时间
* @param today
* @param isFirst true 表示开始时间,false表示结束时间
* @return
*/
public static LocalDateTime getStartOrEndDayOfMonth(LocalDate today, Boolean isFirst) {
String time = MinTime;
LocalDate resDate = LocalDate.now();
if (today == null) {
today = resDate;
}
Month month = today.getMonth();
int length = month.length(today.isLeapYear());
if (isFirst) {
resDate = LocalDate.of(today.getYear(), month, 1);
} else {
resDate = LocalDate.of(today.getYear(), month, length);
time = MinTime;
}
LocalDateTime localDateTime = LocalDateTime.parse(resDate.toString() + time);
return localDateTime;
}
/**
* 本季度的开始/结束时间
* @param today
* @param isFirst true 表示开始时间,false表示结束时间
* @return
*/
public static LocalDateTime getStartOrEndDayOfQuarter(LocalDate today, Boolean isFirst) {
String time = MinTime;
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()));
time = MaxTime;
}
Java获取当天,本周,本月,本季度,本年起始时间工具类
最新推荐文章于 2024-05-11 15:10:09 发布