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<TemporalUnit> +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<TemporalUnit> +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进行增减 判断是否为空 |
使用示例
import java.time.*;
....
//计算两个Temporal对象的时间差
LocalDate date1 = LocalDate.of(1997,1,1);
LocalDate date2 = LocalDate.now();
Period period = Period.between(date1,date2);
System.out.println("date1: "+date1+"\ndate2: "+date2);
System.out.println("Period->years:"+period.getYears()+" months:"+period.getMonths()+" days:"+period.getDays());
-
LocalTime time1 = LocalTime.of(0,0,0);
LocalTime time2 = LocalTime.now();
System.out.println("time1: "+time1+"\ntime2: "+time2);
Duration duration = Duration.between(time1,time2);
System.out.print("Duration->");
duration.getUnits().forEach( temporalUnit -> System.out.print(temporalUnit+": "+duration.get(temporalUnit)+" ") );
结果如下:
date1: 1997-01-01
date2: 2017-02-28
Period->years:20 months:1 days:27
time1: 00:00
time2: 19:21:16.062
Duration->Seconds: 69676 Nanos: 62000000