chronounit類
//注意:若呼叫獲取時、分、秒、半天方法皆報錯獲取當前時間(2021-06-22)
localdate today =localdate.now();
//將string轉localdatetime
datetimeformatter df = datetimeformatter.ofpattern("yyyy-mm-dd");
localdate collecttimedate = localdate.parse("2021-05-01",df);
//判斷相差多少天
log.info("chronounit====相差{}年,相差{}月,相差{}天",
chronounit.years.between(collecttimedate,today),
chronounit.months.between(collecttimedate,today),
chronounit.days.between(collecttimedate,today));
結果:
//結果:獲取當前時間(2021-06-22 17:27:03)
localdatetime today =localdatetime.now();
//將string轉localdatetime
datetimeformatter df = datetimeformatter.ofpattern("yyyy-mm-dd hh:mm:ss");
localdatetime collecttimedate = localdatetime.parse("2021-05-01 16:40:23",df);
//判斷相差多少天
log.info("chronounit====相差{}年,相差{}月,相差{}天",
chronounit.years.between(collecttimedate,today),
chronounit.months.between(collecttimedate,today),
chronounit.days.between(collecttimedate,today));
log.info("chronounit====相差{}小時,相差{}分鐘,相差{}秒",
chronounit.hours.between(collecttimedate,today),
chronounit.minutes.between(collecttimedate,today),
chronounit.seconds.between(collecttimedate,today));
log.info("chronounit====相差{}半天",chronounit.half_days.between(collecttimedate,today));
period類
//注意:period.between方法只接收localdate型別的傳參獲取當前時間(2021-06-22)
localdate todaydate =localdate.now();
//將string轉localdatetime
datetimeformatter dtf = datetimeformatter.ofpattern("yyyy-mm-dd");
localdate lastdate = localdate.parse("2021-05-01",dtf);
//判斷相差多少天
log.info("period====相差{}年,相差{}月,相差{}天",
period.between(lastdate,todaydate).getyears(),
period.between(lastdate,todaydate).getmonths(),
period.between(lastdate,todaydate).getdays());
結果:
從結果中可看到,兩個時間本是相差52天,但此處只顯示相差21天;因為此處只用兩者的日相減,不管年份和月份
duration類
//結果:獲取當前時間(2021-06-22 17:27:03)
localdatetime currentdate =localdatetime.now();
//將string轉localdatetime
datetimeformatter formatter = datetimeformatter.ofpattern("yyyy-mm-dd hh:mm:ss");
localdatetime date = localdatetime.parse("2021-05-01 16:40:23",formatter);
log.info("duration====相差{}天,相差{}小時,相差{}分鐘",
duration.between(date,currentdate).todays(),
duration.between(date,currentdate).tohours(),
duration.between(date,currentdate).tominutes());
以下這種會報錯:
//結果:獲取當前時間(2021-06-22)
localdate currentdate =localdate.now();
//將string轉localdate
datetimeformatter formatter = datetimeformatter.ofpattern("yyyy-mm-dd");
localdate date = localdate.parse("2021-05-01",formatter);
//判斷相差多少天
log.info("duration====相差{}天", duration.between(date,currentdate).todays());
綜上,推薦使用chronounit類
PHP 計算兩個時間戳之間相差的時間
功能 計算兩個時間戳之間相差的日時分秒 begin time 開始時間戳 end time 結束時間戳 function timediff begin time,end time else 計算天數 timediff endtime starttime days intval timediff 86...
PHP 計算兩個時間戳之間相差的時間
功能 計算兩個時間戳之間相差的日時分秒 begin time 開始時間戳 end time 結束時間戳 function timediff begin time,end time else 計算天數 timediff endtime starttime days intval timediff 86...
如何計算兩個日期之間相差的天數?
見msdn 確定兩個日期之間的間隔 visual c 本示例計算兩個日期之間相差的天數並為該差額構造乙個 timespan 值。示例 datetime olddate new datetime 2002,7,15 datetime newdate datetime.now difference in...