JDK8开始新增日期API
概述、LocalTime /LocalDate / LocalDateTime
概述
- 从Java 8开始,java.time包提供了新的日期和时间API,主要涉及的类型有:
- 新增的API严格区分了时刻、本地日期、本地时间,并且,对日期和时间进行运算更加方便。
- 其次,新API的类型几乎全部是不变类型(和String的使用类似),可以放心使用不必担心被修改。
LocalDate、LocalTime、LocalDateTime
他们 分别表示日期,时间,日期时间对象,他们的类的实例是不可变的对象。
他们三者构建对象和API都是通用的
LocalDate、LocalTime、LocalDateTime获取信息的API.
转换相关的API
修改相关的API
Instant
Instant时间戳
JDK8获取时间戳特别简单,且功能更丰富。Instant类由一个静态的工厂方法now()可以返回当前时间戳
时间戳是包含日期和时间的,与java.util.Date很类似,事实上Instant就是类似JDK8 以前的Date。
Instant和Date这两个类可以进行转换。
DateTimeFormatter
在JDK8中,引入了一个全新的日期与时间格式器DateTimeFormatter。
正反都能调用format方法。
代码演示
package com.google.d4_jdk8_time;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* @author North
* @date 2022/10/24 12:26
*/
public class DateTimeFormatDemo {
public static void main(String[] args) {
// 本地此刻 日期时间 对象
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime);
System.out.println("------------------");
// 解析 / 格式化器
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss EE");
// 正向格式化
System.out.println(dateTimeFormatter.format(localDateTime));
// 逆向格式化
System.out.println(localDateTime.format(dateTimeFormatter));
// 解析字符串时间
DateTimeFormatter dateTimeFormatter_1 = DateTimeFormatter.ofPattern("yyyy-dd HH:mm:ss");
// 解析当前字符串时间成为本地日期时间对象
System.out.println(localDateTime.format(dateTimeFormatter_1));
}
}
Duration/Period
Period
- 在Java8中,我们可以使用以下类来计算日期间隔差异:java.time.Period
- 主要是 Period 类方法 getYears(),getMonths() 和 getDays() 来计算,只能精确到年月日。
- 用于 LocalDate 之间的比较。
代码演示
package com.google.d4_jdk8_time;
import java.time.LocalDate;
import java.time.Period;
/**
* @author North
* @date 2022/10/24 12:33
*/
public class PeriodDemo {
public static void main(String[] args) {
// 当前本地 年月日
LocalDate localDate = LocalDate.now();
System.out.println(localDate);
// 生日的 年月日
LocalDate birthDate = LocalDate.of(2001 ,3 ,3);
System.out.println(birthDate);
Period period = Period.between(birthDate , localDate);
System.out.println(period.getYears());
System.out.println(period.getMonths());
System.out.println(period.getDays());
}
}
Duration
- 在Java8中,我们可以使用以下类来计算时间间隔差异:java.time.Duration
- 提供了使用基于时间的值测量时间量的方法。
- 用于 LocalDateTime 之间的比较。也可用于 Instant 之间的比较。
总结
ChronoUnit
java.time.temporal.ChronoUnit
ChronoUnit类可用于在单个时间单位内测量一段时间,这个工具类是最全的了,可以用于比较所有的时间单位