Java8时间与日期API
API设计原因
在Java面世之初,标准库中就引入了两种用于处理日期和时间的类,但是由于很多问题,很多方法都已经弃用,在3avaSE 8中引入java.time包解决了长久以来存在的诸多弊端,java.time包基于Joda-Time库构件,是一种免费的开源解决方法,多年来一直作为处理]ava日其期和时间的事实标准
Java原本自带的java.util.Date和java.util.calendar类
但是这两个类:
- 有线程不安全的风险
- 使用繁杂
- 官方废弃
- 设计烂
故Date类和Calendar早早就被废弃
时间日期常用类概述
- Instant类
Instanit类对时间轴上的单一瞬时点建模,可以用于记录应用程序中的事件时间戳,在之后学习的类型转换中,均可以使用Instant类作为中间类完成转换. - Duration类
Duration类表示秒或纳秒时间间隔,适合处理较短的时间,需要更高的精确性 - Period类
period类表示一段时间的年、月、日 - LocalDate类
LocalDate是一个不可变的日期时间对象,表示日期,通常被视为年月日 - LocalTime类
LocalTime是一个不可变的日期时间对象,代表一个时间,通常被看作是小时-秒,时间表示为纳秒精度 - LocalDateTime类
LocalDateTime是一个不可变的日期时间对象,代表日期时间,通常被视为年-月-日-时-分-秒 - ZonedDateTime类
ZonedDateTime类具有时区的日期时间的不可变表示,此类储存所有日期时间字段,精度为纳秒,时区为区域偏移量,用于处理模糊的本地日期时间 - Year类:表示年
- YearMonth类:表示年月
- MonthDay类:表示月日
创建方法(now)
上述所有类都是线程安全的,并且这些类不提供公共构造函数,即无法用new直接创建而是要使用工厂法实例化
例:
package demo;
import java.time.*;
import java.util.HashMap;
public class TimeDemo1 {
public static void main(String[] args) {
Instant now = Instant.now();
LocalDateTime now1 = LocalDateTime.now();
LocalTime now2 = LocalTime.now();
LocalDate now3 = LocalDate.now();
ZonedDateTime now4 = ZonedDateTime.now();
Year now5 = Year.now();
YearMonth now6 = YearMonth.now();
MonthDay now7 = MonthDay.now();
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put(now.getClass().getName(),now.toString());
hashMap.put(now1.getClass().getName(),now1.toString());
hashMap.put(now2.getClass().getName(),now2.toString());
hashMap.put(now3.getClass().getName(),now3.toString());
hashMap.put(now4.getClass().getName(),now4.toString());
hashMap.put(now5.getClass().getName(),now5.toString());
hashMap.put(now6.getClass().getName(),now6.toString());
hashMap.put(now7.getClass().getName(),now7.toString());
hashMap.forEach((x,y)->{
System.out.println(x+":"+y);
});
}
}
生成自定义的日期时间对象(of)
这里注意ZoneDateTime的of()方法最后传入的是一个ZoneId类的地区偏移量,写法如下:
ZonedDateTime.of(2022, 6, 5, 2, 16, 50,10,ZoneId.of(“+8”));
package demo;
import java.time.*;
import java.util.HashMap;
public class TimeDemo2 {
public static void main(String[] args) {
LocalDate of = LocalDate.of(2000, 10, 16);
LocalTime of1 = LocalTime.of(5, 16, 10);
LocalDateTime of2 = LocalDateTime.of(of, of1);
Year of3 = Year.of(2018);
Month of4 = Month.of(5);
MonthDay of5 = MonthDay.of(8, 16);
ZonedDateTime of6 = ZonedDateTime.of(2022, 6, 5, 2, 16, 50,10,ZoneId.of("+8"));
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put(of.getClass().getName(),of.toString());
hashMap.put(of1.getClass().getName(),of1.toString());
hashMap.put(of2.getClass().getName(),of2.toString());
hashMap.put(of3.getClass().getName(),of3.toString());
hashMap.put(of4.getClass().getName(),of4.toString());
hashMap.put(of5.getClass().getName(),of5.toString());
hashMap.put(of6.getClass().getName(),of6.toString());
hashMap.forEach((x,y)->{
System.out.println(x+":"+y);
})