概述
特点: 线程安全,不可变。
时间日期: 年月日:LocalDate 时分秒:LocalTime 年月日时分秒:LocalDateTime
时间戳:Instant
时间间隔: DateTime,Instant的间隔:Duration LocalDate的间隔:Period
简单操作
当前时间
LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();
Instant instant = Instant.now();
System.out.println(localDate);
System.out.println(localTime);
System.out.println(localDateTime);
System.out.println(instant);
指定时间
LocalDate localDate = LocalDate.of(1234, 1, 2);
LocalTime localTime = LocalTime.of(1, 2, 3);
LocalDateTime localDateTime = LocalDateTime.of(1, 2, 3, 4, 5, 6);
System.out.println(localDate);
System.out.println(localTime);
System.out.println(localDateTime);
今天周几
LocalDateTime now = LocalDateTime.now();
DayOfWeek day = now.getDayOfWeek();
System.out.println(day.toString());
七天后
LocalDateTime now = LocalDateTime.now();
LocalDateTime newTime = now.plusDays(7L);
System.out.println(newTime);
距离2000年1月1日有多久
LocalDate a = LocalDate.of(2000, 1, 1);
LocalDate b = LocalDate.now();
Period result = Period.between(a, b);
System.out.println(result.getYears());
System.out.println(result.getMonths());
System.out.println(result.getDays());
字符串相关
变字符串
LocalDateTime a = LocalDateTime.now();
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
String str = format.format(a);
System.out.println(str);
由字符串得到
String a = "2018-01-13 21:27:30";
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime result = LocalDateTime.parse(a, format);
System.out.println(result);
小案例
距离2000年1月1日有多少天
翻了一下API,日期的间隔无法做到,故用时间的:
LocalDateTime a = LocalDateTime.of(2000, 1, 1, 0, 0, 0);
LocalDateTime b = LocalDateTime.now();
Duration result = Duration.between(a, b);
System.out.println(result.toDays());
|