帮我写一个Springboot基于TemporalAdjusters的ZoneDateTime更加全面的日期工具类
时间: 2023-03-23 15:02:01 浏览: 66
好的,我会尽力回答您的问题。
关于Springboot基于TemporalAdjusters的ZoneDateTime更加全面的日期工具类,您可以考虑实现一个工具类,例如:
```
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
public class DateUtils {
// 获取当前日期时间
public static LocalDateTime getCurrentDateTime() {
return LocalDateTime.now();
}
// 获取指定格式的当前日期时间字符串
public static String getCurrentDateTimeString(String format) {
LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
return dateTime.format(formatter);
}
// 获取指定格式的日期时间字符串
public static String getDateTimeString(LocalDateTime dateTime, String format) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
return dateTime.format(formatter);
}
// 根据指定的年、月、日、时、分、秒获取日期时间
public static LocalDateTime getDateTime(int year, int month, int day, int hour, int minute, int second) {
return LocalDateTime.of(year, month, day, hour, minute, second);
}
// 获取指定日期所在月份的第一天的日期时间
public static LocalDateTime getFirstDayOfMonth(LocalDateTime dateTime) {
return dateTime.with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0).withNano(0);
}
// 获取指定日期所在月份的最后一天的日期时间
public static LocalDateTime getLastDayOfMonth(LocalDateTime dateTime) {
return dateTime.with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59).withNano(999999999);
}
// 获取指定日期所在周的周一的日期时间
public static LocalDateTime getFirstDayOfWeek(LocalDateTime dateTime) {
return dateTime.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).withHour(0).withMinute(0).withSecond(0).withNano(0);
}
// 获取指定日期所在周的周日的日期时间
public static LocalDateTime getLastDayOfWeek(LocalDateTime dateTime) {
return dateTime.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)).withHour(23).withMinute(59).withSecond(59).withNano(999999999);
}
// 计算两个日期时间之间的差,返回秒数
public static long getSecondsBetween(LocalDateTime dateTime1, LocalDateTime dateTime2) {
Duration duration = Duration.between(dateTime1, dateTime2);
return duration.getSeconds();
}
}
```
这个工具类包含了一些常用的日期时间操作方法,例如获取当前日期时间、获取指定格式的日期时间字符串、根据指定的年月日时分秒获取日期时间、获取指定日期所在月份的第一天和最后一天的日期时间、获取指定日期所在周的周一和周日的日期时间、计算两个日期时间之间的差等等。
您可以根据自己的需求对这个工具类进行扩展或修改。希望这个工具类能够对您有所帮助!