原文网址:Java时间系列(JDK8)--LocalDateTime的使用_IT利刃出鞘的博客-CSDN博客
简介
说明
本文用示例来介绍LocalDateTime的用法。
相关网址
LocalDate--使用/教程/实例_IT利刃出鞘的博客-CSDN博客
Java--Period/Duration--使用/教程/实例_IT利刃出鞘的博客-CSDN博客
简述
从Java 8开始,java.time包提供了新的日期和时间API,主要涉及的类型有:
- 本地日期和时间:LocalDateTime,LocalDate,LocalTime;
- 带时区的日期和时间:ZonedDateTime;
- 时刻:Instant;
- 时区:ZoneId,ZoneOffset;
- 时间间隔:Period, Duration。两个类表示两个日期或时间量之间的差
- DateTimeFormatter取代SimpleDateFormat。
和旧API相比,新API严格区分时刻、本地日期、本地时间和带时区的日期时间,对日期和时间运算更加方便。
此外,新API修正了旧API不合理的常量设计:
- Month的范围用1~12表示1月到12月;
- Week的范围用1~7表示周一到周日。
最后,新API的类型全部是不变类型(和String类似),可以放心使用不必担心被修改。
对应的SQL的类型
SQL -> Java
date -> LocalDate
time -> LocalTime
timestamp -> LocalDateTime
常用操作
注意:以下所有用法对于LocalDate和LocalTime是类似的。
创建
根据年、月、日、时、分、秒、纳秒等创建LocalDateTime
eg:
LocalTime zero = LocalTime.of(0, 0, 0); // 00:00:00
LocalTime mid = LocalTime.parse("12:00:00"); // 12:00:00
LocalTime now = LocalTime.now(); // 23:11:08.006
all method
LocalDateTime of(LocalDate date, LocalTime time)
LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute)
LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second)
LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)
LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute)
LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second)
LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)
与Date转换
Date转换为LocalDateTime
Date date = new Date();
LocalDateTime nowDteTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
Date所在包:java.util.Date
LocalDateTime转换为Date
LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
Date date = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
与LocalDate/LocalTime转换
上边是文章的部分内容,为便于维护,全文已转移到此网址:Java时间(JDK8)-LocalDateTime的使用 - 自学精灵