package com.abi.utils;
import lombok.experimental.UtilityClass;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
@UtilityClass
public class DateTimeUtils {
public final String PATTERN_1 = "yyyy-MM-dd HH:mm:ss";
public final String PATTERN_2 = "yyyy-MM-dd";
public final String PATTERN_3 = "yyyy-MM";
/**
* 得到当前月的第一天(yyyy-MM-dd HH:mm:ss)
*/
public LocalDateTime getFirstDayOfMonth() {
return getFirstDayOfMonth(LocalDateTime.now());
}
/**
* 得到指定时间所在月的第一天(yyyy-MM-dd HH:mm:ss)
*/
public LocalDateTime getFirstDayOfMonth(LocalDateTime localDateTime) {
return getStartTimeWithNano0(localDateTime.with(TemporalAdjusters.firstDayOfMonth()));
}
/**
* 得到当前月的最后一天(yyyy-MM-dd HH:mm:ss)
*/
public LocalDateTime getLastDayOfMonth() {
return getLastDayOfMonth(LocalDateTime.now());
}
/**
* 得到指定时间所在月的最后一天(yyyy-MM-dd HH:mm:ss)
*/
public LocalDateTime getLastDayOfMonth(LocalDateTime localDateTime) {
return getEndTimeWithNano0(localDateTime.with(TemporalAdjusters.lastDayOfMonth()));
}
/**
* 得到当前月的前一个月的第一天(yyyy-MM-dd HH:mm:ss)
*/
public LocalDateTime getFirstDayOfLastMonth() {
return getFirstDayOfLastMonth(LocalDateTime.now());
}
/**
* 得到指定时间所在月的前一个月的第一天(yyyy-MM-dd HH:mm:ss)
*/
public LocalDateTime getFirstDayOfLastMonth(LocalDateTime localDateTime) {
return getFirstDayOfMonth(localDateTime.minusMonths(1));
}
/**
* 得到当前月的前一个月的最后一天(yyyy-MM-dd HH:mm:ss)
*/
public LocalDateTime getLastDayOfLastMonth() {
return getLastDayOfLastMonth(LocalDateTime.now());
}
/**
* 得到指定时间所在月的前一个月的最后一天(yyyy-MM-dd HH:mm:ss)
*/
public LocalDateTime getLastDayOfLastMonth(LocalDateTime localDateTime) {
return getLastDayOfMonth(localDateTime.minusMonths(1));
}
/**
* 设置开始时间,不带毫秒,纳秒
*/
public LocalDateTime getStartTimeWithNano0(LocalDateTime localDateTime) {
return localDateTime.withHour(0)
.withMinute(0)
.withSecond(0)
.withNano(0);
}
/**
* 设置结束时间,不带毫秒,纳秒
*/
public LocalDateTime getEndTimeWithNano0(LocalDateTime localDateTime) {
return localDateTime.withHour(23)
.withMinute(59)
.withSecond(59)
.withNano(0);
}
/**
* 格式化
*/
public String format(LocalDateTime localDateTime, String pattern) {
if (localDateTime != null) {
return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
}
return "";
}
/**
* convert Date to LocalDateTime
*/
public LocalDateTime convertToLocalDateTime(Date date) {
if (date != null) {
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}
return null;
}
/**
* convert LocalDateTime to Date
*/
public Date convertToDate(LocalDateTime localDateTime) {
if (localDateTime != null) {
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
return null;
}
}
Java8时间工具类
最新推荐文章于 2024-03-08 14:48:40 发布