🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] # Duration Duration:用于计算两个“时间”间隔,以秒和纳秒为基准 ## 方法 ![](https://box.kancloud.cn/dedfb3aee386c2c798edfa3d9a1ad275_916x267.png) ## 例子 ~~~ LocalDateTime localDateTime = LocalDateTime.now(); LocalDateTime of = LocalDateTime.of(2018, 6, 5, 17, 25, 10); Duration duration = Duration.between(localDateTime, of); System.out.println(duration); //秒数 System.out.println(duration.getSeconds()); //纳秒 System.out.println(duration.getNano()); //相隔的天数 System.out.println(duration.toDays()); ~~~ 输出 ~~~ PT-23H-59M-42.433722S -86383 566278000 0 ~~~ PT那个负的表述少 这边的意思是少23小时,59分钟,后面是秒 # Period Period:用于计算两个“日期”间隔,以年、月、日衡量 ## 方法 ![](https://box.kancloud.cn/54d64200dd6ae2145296b902a57d8ca3_917x272.png) ## 例子 求2个日期相隔的年月日 ~~~ LocalDate localDate = LocalDate.now(); LocalDate localDate1 = LocalDate.of(2017, 3, 5); Period period = Period.between(localDate, localDate1); System.out.println(period); //取年 System.out.println(period.getYears()); //取月 System.out.println(period.getMonths()); //取天 System.out.println(period.getDays()); ~~~ 输出 ~~~ P-1Y-3M-1D -1 -3 -1 ~~~ 指定间隔多少后的Period对象 ~~~ LocalDate localDate = LocalDate.now(); LocalDate localDate1 = LocalDate.of(2017, 3, 5); Period period = Period.between(localDate, localDate1); System.out.println(period); Period period1 = period.withYears(2); System.out.println(period1); ~~~ 输出 ~~~ P-1Y-3M-1D P2Y-3M-1D ~~~