Skip to main content
 首页 » 编程设计

Java localDateTime用法

2022年07月18日25傻小
public static void main(String ... args) { 
        LocalDateTime localDateTime = LocalDateTime.now();

//localDateTime转字符串
String str = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(localDateTime);

// 字符串转localDateTime
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTimeTemp = LocalDateTime.parse("2020-10-10 11:11:11", df);
// 本年本月最后一天
System.out.println(localDateTime.with(TemporalAdjusters.lastDayOfMonth()));
// 本年本月第一天
System.out.println(localDateTime.with(TemporalAdjusters.firstDayOfMonth()));
// 本年下一月第一天
System.out.println(localDateTime.with(TemporalAdjusters.firstDayOfNextMonth()));
// 下一年第一天
System.out.println(localDateTime.with(TemporalAdjusters.firstDayOfNextYear()));
// 本年最后一天
System.out.println(localDateTime.with(TemporalAdjusters.lastDayOfYear()));
// 下一个周五
System.out.println(localDateTime.with(TemporalAdjusters.next(DayOfWeek.FRIDAY)));
// 本月第一个周五
System.out.println(localDateTime.with(TemporalAdjusters.firstInMonth(DayOfWeek.FRIDAY)));
// 本月最后一个周五
System.out.println(localDateTime.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY)));
// 下一个周五,如果当前是周五则返回当前时间
System.out.println(localDateTime.with(TemporalAdjusters.nextOrSame(DayOfWeek.FRIDAY)));
// 前一个周五
System.out.println(localDateTime.with(TemporalAdjusters.previous(DayOfWeek.FRIDAY)));
// 前一个周五,如果当前是周五则返回当前时间
System.out.println(localDateTime.with(TemporalAdjusters.previousOrSame(DayOfWeek.FRIDAY)));
// 当前时间+100天,plusYeas/plusMonths/plusWeeks/plusHours/plusMinutes/plusSeconds形式相同,同于System.out.println(localDateTime.plus(100, ChronoUnit.DAYS));
System.out.println(localDateTime.plusDays(100));
// 当前时间-100天,minusYeas/minusMonths/minusWeeks/minusHours/minusMinutes/minusSeconds形式相同,同于System.out.println(localDateTime.minus(100, ChronoUnit.DAYS));
System.out.println(localDateTime.minusDays(100));

本文参考链接:https://www.cnblogs.com/maohuidong/p/14072872.html