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<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进行增减


判断是否为空

使用示例
   
   
  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







  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值