LocalDateTime
- LocalDateTime和DateTimeFormatter都是线程安全的
import java.time.LocalDateTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
// 当前时刻
LocalDateTime rightNow = LocalDateTime.now();
rightNow.toString(); // 2021-12-20T19:36:46.199019500
rightNow.getYear(); // 2021
rightNow.getMonth(); // DECEMBER
rightNow.getDayOfYear(); // 354
rightNow.getDayOfMonth(); // 20
rightNow.getDayOfWeek(); // MONDAY
rightNow.getHour(); // 19
rightNow.getMinute(); // 36
rightNow.getSecond(); // 46
// 构造
LocalDateTime oneDay = LocalDateTime.of(2021, Month.DECEMBER, 20, 19, 38, 0);
System.out.println(oneDay); // 2021-12-20T19:38
// 修改日期
rightNow = oneDay.minusYears(1)
.plusMonths(2)
.withDayOfMonth(10)
.withHour(12);
System.out.println(rightNow); // 2021-02-10T12:38
// 格式化日期
rightNow.format(DateTimeFormatter.ISO_DATE); // 2021-02-10
rightNow.format(DateTimeFormatter.ofPattern("yyyy/MM/dd")); // 2021/02/10
// 解析
LocalDateTime.parse("2021/02/10 11:21", DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm")); // 2021-02-10T11:21
}
}