Instant和Duration、Period-java8新特性

[java8新特性]

Instant : 时间戳
Duration : 用于计算两个“时间”间隔
Period : 用于计算两个“日期”间隔

System.out.println(Instant.now()); //默认使用UTC时区:2019-01-24T14:01:32.258Z
System.out.println(Instant.now().atOffset(ZoneOffset.ofHours(8)));//加8个小时等于中国时间:2019-01-24T22:01:32.258+08:00

System.out.println(Instant.now().getEpochSecond()); // 秒:1548338627
System.out.println(Instant.now().toEpochMilli());   // 毫秒:1548338627885
System.out.println(Instant.now().getNano());        // 纳秒:885000000

// 使用Unix 1970-01-01T00:00:00Z所经历的毫秒值
System.out.println(Instant.ofEpochSecond(60));  	// 秒:1970-01-01T00:01:00Z
System.out.println(Instant.ofEpochSecond(60,60));   // 秒,纳秒: 1970-01-01T00:01:00.000000060Z
System.out.println(Instant.ofEpochMilli(60));   	// 毫秒:1970-01-01T00:00:00.060Z
System.out.println(Instant.MAX);    // 最大时间戳:+1000000000-12-31T23:59:59.999999999Z
System.out.println(Instant.MIN);    // 最小时间戳:-1000000000-01-01T00:00:00Z

// Duration:用于计算两个“时间”间隔
Instant startTime = Instant.now();
try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
}
Instant endTime = Instant.now();
Duration duration = Duration.between(startTime, endTime);
System.out.println("所耗费时间为:" + duration);
// 一样的get获取,plus加时间,minus减时间...

// Period : 用于计算两个“日期”间隔
LocalDate startDate = LocalDate.of(2019, 1, 1);
LocalDate endDate = LocalDate.now();

Period period = Period.between(startDate, endDate);
System.out.println(period);
// 一样的get获取,plus加时间,minus减时间...

其它特性或API,可查阅JDK1.8API或参考本人其它文章,另本人有中文版JDK1.8API可以参考我的分享文章

猜你喜欢

转载自blog.csdn.net/han12398766/article/details/86634332
今日推荐