Java8 新日期时间类(3)

java.time 时间日期偏移类

java.time处理本地日期时间偏移的主要类为 java.time.Duration,java.time.Period  ;
  • Period - 处理有关基于时间的日期数量。

  • Duration - 处理有关基于时间的时间量


Duration
静态构造方式摘要
static Duration

static Duration 
static Duration

between(LocalTime startInclusive,LocalTime endExclusive)

of(long amount,TemporalUnit unit)
ofHours(long hours)
ofMinutes(long minutes)
ofSeconds(long seconds)
使用两个时间类的时间差产生Duration,Temporal包括LocalDateTime,ZonedDateTime等

使用指定TemperalUnit创建Duration


成员方法摘要
+long


+Duration
+long
+List

+Duration



+boolean
toHours() / toMinutes() /toSeconds()
toMillis()  / toNanos()

withSeconds(long seconds)
getSeconds() / getNanos()
getUnits()

plus
(long amountToAdd,TemporaUnit unit)
plusHours(long)/plusMinute(long)/plusSeconds(long)

isZero()
将Duration转化为相应单位的数值


修改数值
获取数值(效果同toSeconds,toNanos)
获取参数表

对Duration进行增减



检验值是否为0


Period
静态构造方式摘要
static Period

static Period
static Period

between(LocalDate startInclusive,LocalDate endExclusive)

of(int years,int months,int days)
ofYears(long hours)
ofMonths(long minutes)
ofDayss(long seconds)
使用两个时间类的时间差产生Duration,Temporal包括LocalDateTime,ZonedDateTime等

使用指定数值创建Period


成员方法摘要
+long


+Period
+List
+long 

+Period


+boolean
toTotalMonths()

withDays
(long seconds)/withMonths/withYears
getUnits()
getYears() / getMonths() / getDays()


plus
(long amountToAdd,TemporaUnit unit)
plusDays(long)/plusMonths(long)/plusYears(long)
isZero()
将Period转化为相应单位的数值


修改数值
获取参数表
获取参数

对Period进行增减


判断是否为空

使用示例
 
    
  1. import java.time.*;
  2. ....
  3. //计算两个Temporal对象的时间差
  4. LocalDate date1 = LocalDate.of(1997,1,1);
  5. LocalDate date2 = LocalDate.now();
  6. Period period = Period.between(date1,date2);
  7. System.out.println("date1: "+date1+"\ndate2: "+date2);
  8. System.out.println("Period->years:"+period.getYears()+" months:"+period.getMonths()+" days:"+period.getDays());
  9. LocalTime time1 = LocalTime.of(0,0,0);
  10. LocalTime time2 = LocalTime.now();
  11. System.out.println("time1: "+time1+"\ntime2: "+time2);
  12. Duration duration = Duration.between(time1,time2);
  13. System.out.print("Duration->");
  14. duration.getUnits().forEach( temporalUnit -> System.out.print(temporalUnit+": "+duration.get(temporalUnit)+" ") );

结果如下:
 
     
  1. date1: 1997-01-01
  2. date2: 2017-02-28
  3. Period->years:20 months:1 days:27
  4. time1: 00:00
  5. time2: 19:21:16.062
  6. Duration->Seconds: 69676 Nanos: 62000000







你可能感兴趣的:(Java,Java,8新特性)