簡介:
Java8 Date/Time API相關(guān)的類:LocalDate殴穴,LocalTime螟凭,LocalDateTime勘高,這三個(gè)類有一個(gè)公共特點(diǎn)就是同String類一樣鸽嫂,都是密封類(final修飾),不允許繼承(都位于java.time包下)
Java8之前常用SimpleDateFormat dateformat = new SimpleDateFormat(new Date());的方式來格式化時(shí)間髓窜,程序中出現(xiàn)大量的SimpleDateFormat類扇苞,既不簡潔實(shí)用,造成代碼臃腫寄纵,且可讀性非常低
Java8以前使用new Date()獲取月時(shí)鳖敷,從0開始,每次都要+1程拭,獲取本月最后一天定踱,要分情況判斷28,29恃鞋,30崖媚,31亦歉,非常麻煩,代碼量非常繁瑣畅哑。Java8中的?Date/Time API?使得這些問題都解決了
獲取當(dāng)前日期:
LocalTime.now(); // 獲取當(dāng)前時(shí)間 format: HH:mm:ss 輸出:10:13:11.241
LocalDateTime.now(); // 獲取當(dāng)前日期時(shí)間 format: yyyy-MM-dd HH:mm:ss 輸出:2019-02-20T10:13:11.241
LocalDate.now();// 獲取當(dāng)前日期 format: yyyy-MM-dd 輸出:2019-02-20
三肴楷、LocalDate API
獲取當(dāng)前日期
LocalDate nowDate = LocalDate.now();// 輸出 2019-02-20
自定義時(shí)間
LocalDate formatDate = LocalDate.parse("2019-01-01");// 輸出 2019-01-01
獲取當(dāng)前是本月的第幾天
int dayOfMonth = nowDate.getDayOfMonth();// 輸出 20
獲取當(dāng)前天是本年的第幾天
int dayOfYear = nowDate.getDayOfYear();// 輸出 51
獲取當(dāng)天所屬本周的周幾
DayOfWeek dayOfWeek = nowDate.getDayOfWeek();// 輸出 WEDNESDAYint value = nowDate.getDayOfWeek().getValue();// 輸出 3
獲取當(dāng)月所屬本年的第幾月,與new Date()相比它是從1開始荠呐,拋棄了之前的從0開始
Month month = nowDate.getMonth();// 輸出 FEBRUARYint value = nowDate.getMonth().getValue();// 輸出 2int monthValue = nowDate.getMonthValue();// 輸出 2
獲取年份
int year = nowDate.getYear();// 輸出 2021
獲取本月第一天
LocalDate firstDayOfMonth= nowDate.with(TemporalAdjusters.firstDayOfMonth());// 輸出 2021-02-01
獲取本月最后一天(無須再判斷當(dāng)月是28赛蔫、29、30泥张、31天)LocalDate with(TemporalAdjuster adjuster)?: 返回此日期的調(diào)整副本
LocalDate lastDayOfMonth = nowDate.with(TemporalAdjusters.lastDayOfMonth());// 輸出 2021-02-28
使用自定義格式器DateTimeFormatter替換了Java8之前的SimpleDateFormat
String nowDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"));// 輸出 2019-02-20 11:17:35