生活随笔
收集整理的這篇文章主要介紹了
JDK8的日期时间类3
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
計算兩個時間的間隔
方法:between【靜態(tài)方法】
1.獲取相隔的年月日用Period調用,參數(shù)用LocalDate類對象封裝的時間
2.獲取相隔的天年月日用Duration調用,參數(shù)用LocalDateTime類對象封裝的時間
public class Demo7 {public static void main(String
[] args
) {LocalDateTime ldt1
= LocalDateTime
.of(2021, 06, 29, 10, 10, 10);LocalDateTime ldt2
= LocalDateTime
.of(2021, 11, 11, 00, 00, 00);Period period
= Period
.between(ldt1
.toLocalDate(),ldt2
.toLocalDate());System
.out
.println("還有"+period
.getYears()+"年 "+period
.getMonths()+"月 "+period
.getDays()+"天 ");Duration duration
= Duration
.between(ldt1
, ldt2
);System
.out
.println(duration
.toDaysPart()+"天"+duration
.toHoursPart()+"時 "+duration
.toMinutesPart()+"分 "+duration
.toSecondsPart()+"秒 ");System
.out
.println(duration
.toMinutesPart());System
.out
.println(duration
.toSecondsPart());}
}打印結果:
----------------------------------------------------------------------
還有
0年
4月
13天
134天
13時
49分
50秒
49
50
判斷一個字符串的時間是否為閏年
題目:定義一個時間字符串"2000-08-08 08:08:08",求這一年是平年還是閏年
思路:
(1)使用LocalDateTime的parse方法,解析為LocalDateTime對象
(2)把LocalDateTime的時間設置到2000年的3月1日,再減1天就到了二月的最后一天,再獲取這一天的是幾號,如果是28就是平年,否則就是閏年
實現(xiàn):
public class Test3 {public static void main(String
[] args
) {String str
="2000-08-08 08:08:08";LocalDateTime parse
= LocalDateTime
.parse(str
, DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss"));LocalDateTime ldt
= parse
.withMonth(3).withDayOfMonth(1).plusDays(-1);int dayOfMonth
= ldt
.getDayOfMonth();System
.out
.println(dayOfMonth
);if(dayOfMonth
==28){System
.out
.println("平年");}else {System
.out
.println("閏年");}}
}打印結果:
----------------------------------------------------------------------
29
閏年
總結
以上是生活随笔為你收集整理的JDK8的日期时间类3的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。