深入理解Java8新特性之新日期時(shí)間API的應(yīng)用
1.新舊對(duì)比(線程安全問題)
我們先來看下面的代碼:👇👇👇 (關(guān)于代碼中某些類中的某些方法,我在這里就不說了,大家可以去查找api文檔)
package com.szh.java8.datetime; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.*; /** * */ public class TestSimpleDateFormat { public static void main(String[] args) throws ExecutionException, InterruptedException { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); Callable<Date> task1 = new Callable<Date>() { @Override public Date call() throws Exception { return sdf.parse("20211109"); } }; ExecutorService pool1 = Executors.newFixedThreadPool(10); List<Future<Date>> futureList1 = new ArrayList<>(); for (int i = 0; i < 10; i++) { futureList1.add(pool1.submit(task1)); } for (Future<Date> future : futureList1) { System.out.println(future.get()); } pool1.shutdown(); //================================================================= // DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd"); // // Callable<LocalDate> task2 = new Callable<LocalDate>() { // @Override // public LocalDate call() throws Exception { // return LocalDate.parse("20211109",dtf); // } // }; // // ExecutorService pool2 = Executors.newFixedThreadPool(10); // List<Future<LocalDate>> futureList2 = new ArrayList<>(); // for (int i = 0; i < 10; i++) { // futureList2.add(pool2.submit(task2)); // } // // for (Future<LocalDate> future : futureList2) { // System.out.println(future.get()); // } // // pool2.shutdown(); } }
運(yùn)行之后,就出現(xiàn)了線程安全問題。
將代碼中的上半部分注釋掉,然后打開下半部分的代碼,再次運(yùn)行,線程安全問題就不存在了。
也就是Java8中提供了新一套日期時(shí)間API已經(jīng)解決了線程安全問題。
2.LocalDate
package com.szh.java8.datetime; import java.time.LocalDate; /** * */ public class TestLocalDate { public static void main(String[] args) { LocalDate ld1 = LocalDate.now(); System.out.println(ld1); LocalDate ld2 = LocalDate.of(2021,5,1); System.out.println(ld2); LocalDate ld3 = ld1.plusYears(20); System.out.println(ld3); LocalDate ld4 = ld1.minusMonths(3); System.out.println(ld4); System.out.println(ld1.isBefore(ld2)); System.out.println(ld2.isAfter(ld1)); System.out.println(ld1.isLeapYear()); System.out.println("年:" + ld1.getYear() + ", 月:" + ld1.getMonth() + ", 日:" + ld1.getDayOfMonth()); System.out.println("年:" + ld1.getYear() + ", 月:" + ld1.getMonthValue() + ", 日:" + ld1.getDayOfMonth()); } }
3.LocalTime
package com.szh.java8.datetime; import java.time.LocalTime; /** * */ public class TestLocalTime { public static void main(String[] args) { LocalTime lt1 = LocalTime.now(); System.out.println(lt1); LocalTime lt2 = LocalTime.of(13,14,15); System.out.println(lt2); LocalTime lt3 = lt2.plusHours(3); System.out.println(lt3); LocalTime lt4 = lt2.minusMinutes(14); System.out.println(lt4); System.out.println(lt1.isBefore(lt2)); System.out.println(lt2.isAfter(lt1)); System.out.println("小時(shí):" + lt1.getHour() + ", 分鐘:" + lt1.getMinute() + ", 秒:" + lt1.getSecond()); } }
4.LocalDateTime
package com.szh.java8.datetime; import java.time.LocalDateTime; /** * */ public class TestLocalDateTime { public static void main(String[] args) { LocalDateTime ldt1 = LocalDateTime.now(); System.out.println(ldt1); LocalDateTime ldt2 = LocalDateTime.of(2020,5,1,13,14,15); System.out.println(ldt2); LocalDateTime ldt3 = ldt1.plusYears(15); System.out.println(ldt3); LocalDateTime ldt4 = ldt1.minusDays(20); System.out.println(ldt4); System.out.println(ldt1.isBefore(ldt2)); System.out.println(ldt2.isAfter(ldt1)); System.out.println("年:" + ldt2.getYear() + ", 月:" + ldt2.getMonthValue() + ", 日:" + ldt2.getDayOfMonth() + ", 小時(shí):" + ldt2.getHour() + ", 分鐘:" + ldt2.getMinute() + ", 秒:" + ldt2.getSecond()); } }
5.Instant
package com.szh.java8.datetime; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; /** * Instant : 時(shí)間戳(使用 Unix 元年 1970年1月1日 00:00:00 所經(jīng)歷的毫秒值) * 默認(rèn)使用 UTC 時(shí)區(qū) */ public class TestInstant { public static void main(String[] args) { Instant instant1 = Instant.now(); System.out.println(instant1); OffsetDateTime odt = instant1.atOffset(ZoneOffset.ofHoursMinutesSeconds(8,16,32)); System.out.println(odt); System.out.println(instant1.getEpochSecond()); System.out.println(instant1.toEpochMilli()); Instant instant2 = Instant.ofEpochSecond(1000); System.out.println(instant2); Instant instant3 = instant1.plusSeconds(30); System.out.println(instant3); Instant instant4 = instant1.minusSeconds(50); System.out.println(instant4); } }
6.Duration、Period
package com.szh.java8.datetime; import java.time.Duration; import java.time.LocalDate; import java.time.LocalTime; import java.time.Period; /** * Period : 用于計(jì)算兩個(gè)“日期”間隔 * Duration : 用于計(jì)算兩個(gè)“時(shí)間”間隔 */ public class TestPeriodDuration { public static void main(String[] args) { LocalDate ld1 = LocalDate.now(); LocalDate ld2 = LocalDate.of(2020,5,1); Period period = Period.between(ld2,ld1); System.out.println("兩個(gè)日期相差:" + period.getYears() + "年," + period.getMonths() + "個(gè)月," + period.getDays() + "天...."); System.out.println(period.isNegative()); //檢查此期間的三個(gè)單位是否為負(fù) System.out.println(period.isZero()); //檢查此期間的所有三個(gè)單位是否為零 System.out.println("--------------------------------------------"); LocalTime lt1 = LocalTime.now(); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } LocalTime lt2 = LocalTime.now(); Duration duration = Duration.between(lt1,lt2); System.out.println("兩個(gè)時(shí)間相差:" + duration.toHours() + "個(gè)小時(shí)," + duration.toMinutes() + "分鐘," + duration.getSeconds() + "秒...."); System.out.println(duration.isNegative()); //檢查此期間的三個(gè)單位是否為負(fù) System.out.println(duration.isZero()); //檢查此期間的所有三個(gè)單位是否為零 } }
7.TestTemporalAdjuster、TestTemporalAdjusters
package com.szh.java8.datetime; import java.time.DayOfWeek; import java.time.LocalDateTime; import java.time.temporal.TemporalAdjusters; /** * TemporalAdjuster : 時(shí)間校正器。有時(shí)我們可能需要獲取例如:將日期調(diào)整到“下個(gè)周日”等操作。 * TemporalAdjusters : 該類通過靜態(tài)方法提供了大量的常用 TemporalAdjuster 的實(shí)現(xiàn)。 */ public class TestTemporalAdjuster { public static void main(String[] args) { LocalDateTime ldt1 = LocalDateTime.now(); System.out.println(ldt1); LocalDateTime ldt2 = ldt1.withMonth(5); System.out.println(ldt2); LocalDateTime ldt3 = ldt1.with(TemporalAdjusters.next(DayOfWeek.SATURDAY)); System.out.println(ldt3); //自定義:下一個(gè)工作日 LocalDateTime ldt4 = ldt1.with((l) -> { LocalDateTime ldt5 = (LocalDateTime) l; DayOfWeek dow = ldt5.getDayOfWeek(); if (dow.equals(DayOfWeek.FRIDAY)) { return ldt5.plusDays(3); } else if (dow.equals(DayOfWeek.SATURDAY)) { return ldt5.plusDays(2); } else { return ldt5.plusDays(1); } }); System.out.println(ldt4); } }
8.DateTimeFormatter
package com.szh.java8.datetime; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** * 解析與格式化 */ public class TestDateTimeFormatter { public static void main(String[] args) { DateTimeFormatter dtf1 = DateTimeFormatter.ISO_LOCAL_DATE_TIME; LocalDateTime ldt1 = LocalDateTime.now(); String strDate1 = ldt1.format(dtf1); System.out.println(strDate1); System.out.println("-----------------------------------"); DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss"); String strDate2 = ldt1.format(dtf2); System.out.println(strDate2); System.out.println("-----------------------------------"); LocalDateTime newDate = ldt1.parse(strDate2, dtf2); System.out.println(newDate); } }
以上就是深入理解Java8新特性之新日期時(shí)間API的應(yīng)用的詳細(xì)內(nèi)容,更多關(guān)于Java 日期時(shí)間API的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
java json字符串轉(zhuǎn)JSONObject和JSONArray以及取值的實(shí)例
這篇文章主要介紹了java json字符串轉(zhuǎn)JSONObject和JSONArray以及取值的實(shí)例的相關(guān)資料,需要的朋友可以參考下2017-05-05Spring Cloud構(gòu)建Eureka應(yīng)用的方法
這篇文章主要介紹了Spring Cloud構(gòu)建Eureka應(yīng)用的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-03-03java如何實(shí)現(xiàn)嵌套對(duì)象轉(zhuǎn)大map(扁平化)
這篇文章主要介紹了java如何實(shí)現(xiàn)嵌套對(duì)象轉(zhuǎn)大map(扁平化),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10淺談一下maven優(yōu)缺點(diǎn)及使用和特點(diǎn)
這篇文章主要介紹了淺談一下maven優(yōu)缺點(diǎn)及使用和特點(diǎn),一個(gè)項(xiàng)目管理工具軟件,那么maven項(xiàng)目有什么優(yōu)缺點(diǎn)呢,讓我們一起來看看吧2023-03-03微服務(wù)中使用Maven BOM來管理你的版本依賴詳解
這篇文章主要介紹了微服務(wù)中使用Maven BOM來管理你的版本依賴,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12Java應(yīng)用多機(jī)器部署解決大量定時(shí)任務(wù)問題
這篇文章主要介紹了Java應(yīng)用多機(jī)器部署解決大量定時(shí)任務(wù)問題,兩臺(tái)服務(wù)器同時(shí)部署了同一套代碼, 代碼中寫有spring自帶的定時(shí)任務(wù),但是每次執(zhí)行定時(shí)任務(wù)時(shí)只需要一臺(tái)機(jī)器去執(zhí)行,需要的朋友可以參考下2019-07-07