1、为什么要新增jdk8时间类
jdk7以前的代码较为繁琐,jdk8以后代码进行简化。
jdk7多线程情况下会导致数据安全问题,jdk8中时间日期对象都是不可变得,解决了这个问题。
ZoneId
public static void main(String[] args) {
//获得所有时区的系统名称
Set<String> zoneIds= ZoneId.getAvailableZoneIds();
System.out.println(zoneIds.size());
System.out.println(zoneIds);
//获取系统的默认时区
ZoneId zoneId=ZoneId.systemDefault();
System.out.println(zoneId);
//获取指定的时区
ZoneId zoneId1=ZoneId.of("Asia/Pontianak");
System.out.println(zoneId1);
}
Instant
public static void main(String[] args) {
//获取当前时间的Instant对象
Instant now=Instant.now();
System.out.println(now);
//根据秒/毫秒/纳秒获得时间Instant对象
Instant instant2=Instant.ofEpochMilli(1L);
System.out.println(instant2);
//只有静态的才可以用类名调用,比如说static(final可以吗?)。非静态的需要使用对象进行调用
//指定时区
ZonedDateTime zonedDateTime=Instant.now().atZone(ZoneId.of("Asia/Shanghai"));
System.out.println(zonedDateTime);
//isxxxx判断
Instant instant3=Instant.ofEpochMilli(0L);
Instant instant4=Instant.ofEpochMilli(500L);
boolean result= instant3.isBefore(instant4);//判断3时间是不是在4的前面
System.out.println(result);
boolean result1=instant3.isAfter(instant4);//判断3时间是不是在4的后面
System.out.println(result1);
//增加删减时间->为了线程安全,修改后会直接创建一个新的对象
Instant instant6=Instant.ofEpochMilli(5000L);
System.out.println(instant6);
Instant instant7=instant6.minusSeconds(1);
System.out.println(instant7);
}
DateTimeFormatter
public static void main(String[] args) {
/*
static DateTimeFormatter ofPattern()获取格式对象
String format(时间对象)按照指定方式格式化
*/
//获取时间对象
ZonedDateTime time= Instant.now().atZone(ZoneId.of("Asia/Shanghai"));
//解析/格式化
DateTimeFormatter dtf1=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss EE a");
//格式化
System.out.println(dtf1.format(time));
}
ZoneDateTime
public static void main(String[] args) {
/*
static ZoneDateTime now()根据当前时间创建对象
static ZoneDateTime ofxxx()根据指定时间创建对象
ZoneDateTime withxxx()修改时间系列的方法
ZoneDateTime minusxxx()减少时间
ZoneDateTime plusxxx()增加时间
*/
//1、获取当前时间对象(带时区)
ZonedDateTime zonedDateTime=ZonedDateTime.now();
System.out.println(zonedDateTime);
//2、获取指定的时间对象(带时区)
//年月日时分秒方式指定
ZonedDateTime time1=ZonedDateTime.of(2023,10,1,11,12,12,0, ZoneId.of("Asia/Shanghai"));
System.out.println(time1);
//通过Instant+时区的方法获取指定对象
Instant instant=Instant.ofEpochMilli(0L);
ZoneId zoneId=ZoneId.of("Asia/Shanghai");
ZonedDateTime time2=ZonedDateTime.ofInstant(instant,zoneId);
System.out.println(time2);
//3withxxx修改时间
ZonedDateTime zonedDateTime2=time2.withYear(2000);
System.out.println(zonedDateTime2);
//4减少时间
ZonedDateTime zonedDateTime3=time2.minusYears(200);
System.out.println(zonedDateTime3);
//5增加时间
ZonedDateTime zonedDateTime4=time2.plusYears(200);
System.out.println(zonedDateTime4);
/*
细节:jdk8中我们修改增加减少的时间,不会修改调用者本身,而是创建一个新的时间对象
*/
}