1. 程式人生 > >JAVA 8 主要新特性 ----------------(七)新時間日期 API ----- Duration “時間”間隔

JAVA 8 主要新特性 ----------------(七)新時間日期 API ----- Duration “時間”間隔

 

 

Duration:用於計算兩個“時間”間隔

簡介:

   

 

用法:

1、Zero常量

 

例項:

1 Duration duration = Duration.ZERO;
2         System.out.println("持續時間常量值:"+duration.toNanos());
3         System.out.println("持續時間常量值是否為零:"+duration.isZero());
4         System.out.println("持續時間常量值是正數:"+duration.abs().toNanos());
View Code

2、ofDays

 例項:

1 Duration durationOfDays =  Duration.ofDays(1);
2         System.out.println("一天有多少小時:"+durationOfDays.toHours()+"H");
View Code

3、ofHours

 

 例項:

1 Duration durationOfHours =  Duration.ofHours(2);
2         System.out.println("一小時有多少分:"+durationOfHours.toMinutes()+"m");
View Code

4、ofMinutes

例項:

1 Duration durationOfMinutes =  Duration.ofMinutes(1);
2         System.out.println("一分鐘有多少秒:"+durationOfMinutes.getSeconds()+"s");
View Code

5、ofSeconds

例項:

 

1 Duration durationOfSeconds =  Duration.ofSeconds(1);
2         System.out.println("一秒有多少秒:"+durationOfSeconds.getSeconds()+"s");
View Code

 

例項:

1 Duration durationOfSecondsNano =  Duration.ofSeconds(2,2000);
2         System.out.println("2000納秒有多少秒:"+durationOfSecondsNano.getSeconds()+"s");
View Code

6、ofMillis

 例項:

1 Duration durationOfMillis =  Duration.ofMillis(5000);
2         System.out.println("5000納秒有多少秒:"+durationOfMillis.getSeconds()+"s");
View Code

7、ofNanos

 例項:

1 Duration durationOfNanos =  Duration.ofNanos(10000);
2         System.out.println("10000納秒有多少納秒:"+durationOfNanos.toNanos()+"s");
View Code

8、of

例項:

1  Duration durationOf =  Duration.of(10,SECONDS);
2         System.out.println("10秒有多少秒:"+durationOf.getSeconds()+"s");
View Code

9、from

例項:

1 Duration durationFrom =  Duration.from(Duration.ofDays(10));
2         System.out.println("10天有多少小時:"+durationFrom.toHours()+"H");
View Code

10、parse

 

例項:

1 Duration durationParse =  Duration.parse("PT15M");
2         System.out.println("格式轉化15分鐘:"+durationParse.toMinutes()+"M");
View Code

11、between

 

例項:

1 Duration durationBetween =  Duration.between(LocalTime.NOON,LocalTime.MAX);
2         System.out.println("距離今天結束還有多少時間:"+durationBetween.toHours()+"時"+durationBetween.toMinutes()+"分"+durationBetween.getSeconds()+"秒");
View Code