直接上例子
@Test
public void test1(){
// 获取当前时间的两种方法
LocalDateTime now = LocalDateTime.now();
LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault());
System.out.println(now);
System.out.println(localDateTime);
// 指定具体日期
LocalDateTime time1 = LocalDateTime.of(2019, 1, 22, 14, 3, 20);
System.out.println(time1);
}
结果如下, 注意 LocalDateTime输出形式
2019-12-13T09:48:48.410
2019-12-13T09:48:48.410
2019-01-22T14:03:20
String和 LocalDateTime 互相转换
@Test
public void test2(){
// LocalDateTime 转String
LocalDateTime time1 = LocalDateTime.of(2019, 1, 22, 14, 3, 20);
String timeStr1 = time1.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println(timeStr1);
// String 转 LocalDateTime, 注意把 yyyy-MM-dd HH:mm:ss 中空格地方换为字符'T'
timeStr1 = timeStr1.replace(' ', 'T');
System.out.println("timeStr1:" + timeStr1);
LocalDateTime time2 = LocalDateTime.parse(timeStr1);
System.out.println(time2);
}
LocalDateTime 的偏移
@Test
public void test3(){
// 年月日时分秒, 都可作为偏移单位; 可以偏移负数
LocalDateTime time1 = LocalDateTime.of(2019, 1, 22, 14, 3, 20);
System.out.println(time1.plusDays(-20));
System.out.println(time1.plusHours(10));
System.out.println(time1.plusMinutes(-10));
System.out.println(time1.plusMonths(1));
System.out.println(time1.plusSeconds(11));
System.out.println(time1.plusYears(2));
}
LocalDateTime 取日期相关值 以及日期先后的比较
@Test
public void test4(){
LocalDateTime time1 = LocalDateTime.of(2019, 1, 22, 14, 3, 20);
// 从LocalDateTime 直接取值
System.out.println(time1.getDayOfMonth());
System.out.println(time1.getHour());
System.out.println(time1.getMonthValue());
// LocalDateTime的比较
System.out.println(LocalDateTime.now().isAfter(time1));
}
比较LocalDateTime 之间的时间间隔
@Test
public void test5(){
// 使用 Duration 比较时间间隔(向下取整)
LocalDateTime time1 = LocalDateTime.of(2019, 1, 22, 14, 3, 20);
Duration between = Duration.between(time1, LocalDateTime.now());
System.out.println(between);
System.out.println(between.toDays());
System.out.println(between.toHours());
System.out.println(between.getSeconds());
System.out.println(between.toMillis());
}