Java 8新時(shí)間日期庫java.time的使用示例
- Instant——它代表的是時(shí)間戳
- LocalDate——不包含具體時(shí)間的日期,比如 2020-01-14。它可以用來存儲(chǔ)生日,周年紀(jì)念日,入職日期等。
- LocalTime——它代表的是不含日期的時(shí)間
- LocalDateTime——它包含了日期及時(shí)間,不過還是沒有偏移信息或者說時(shí)區(qū)。
- ZonedDateTime——這是一個(gè)包含時(shí)區(qū)的完整的日期時(shí)間,偏移量是以 UTC / 格林威治時(shí)間為基準(zhǔn)的。
Java 8 是如何處理時(shí)間及日期的
示例 1 如何 在 Java 8 中獲取當(dāng)天的日期
LocalDate today = LocalDate.now(); System.out.println("Today's Local date : " + today); Output Today's Local date : 2020-01-14
示例 2 如何在 Java 8 中獲取當(dāng)前的年月日
LocalDate today = LocalDate.now(); int year = today.getYear(); int month = today.getMonthValue(); int day = today.getDayOfMonth(); System.out.printf("Year : %d Month : %d day : %d \t %n", year, month, day); Output Today's Local date : 2020-01-14 Year : 2020 Month : 1 day : 14
示例 3 在 Java 8 中如何獲取某個(gè)特定的日期
LocalDate dateOfBirth = LocalDate.of(2010, 01, 14); System.out.println("Your Date of birth is : " + dateOfBirth); Output : Your Date of birth is : 2010-01-14
示例 4 在 Java 8 中如何檢查兩個(gè)日期是否相等
LocalDate date1 = LocalDate.of(2020, 01, 14); if(date1.equals(today)){ System.out.printf("Today %s and date1 %s are same date %n", today, date1); } Output today 2020-01-14 and date1 2020-01-14 are same date
示例 5 在 Java 8 中如何檢查重復(fù)事件,比如說生日
LocalDate dateOfBirth = LocalDate.of(2010, 01, 14); MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth()); MonthDay currentMonthDay = MonthDay.from(today); if(currentMonthDay.equals(birthday)){ System.out.println("Many Many happy returns of the day !!"); }else{ System.out.println("Sorry, today is not your birthday"); } Output: Many Many happy returns of the day !!
示例 6 如何在 Java 8 中獲取當(dāng)前時(shí)間
LocalTime time = LocalTime.now(); System.out.println("local time now : " + time); Output local time now : 16:33:33.369 // in hour, minutes, seconds, nano seconds
示例 7 如何增加時(shí)間里面的小時(shí)數(shù)
LocalTime time = LocalTime.now(); LocalTime newTime = time.plusHours(2); // adding two hours System.out.println("Time after 2 hours : " + newTime); Output : Time after 2 hours : 18:33:33.369
示例 8 如何獲取 1 周后的日期
LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS); System.out.println("Today is : " + today); System.out.println("Date after 1 week : " + nextWeek); Output: Today is : 2020-01-14 Date after 1 week : 2020-01-21
示例 9 一年前后的日期
LocalDate previousYear = today.minus(1, ChronoUnit.YEARS); System.out.println("Date before 1 year : " + previousYear); LocalDate nextYear = today.plus(1, YEARS); System.out.println("Date after 1 year : " + nextYear); Output: Date before 1 year : 2019-01-14 Date after 1 year : 2021-01-14
示例 10 在 Java 8 中使用時(shí)鐘
// Returns the current time based on your system clock and set to UTC. Clock clock = Clock.systemUTC(); System.out.println("Clock : " + clock); // Returns time based on system clock zone Clock defaultClock = Clock.systemDefaultZone(); System.out.println("Clock : " + clock); Output: Clock : SystemClock[Z] Clock : SystemClock[Z] public class MyClass { private Clock clock; // dependency inject ... public void process(LocalDate eventDate) { if(eventDate.isBefore(LocalDate.now(clock)) { ... } } }
示例 11 在 Java 中如何判斷某個(gè)日期是在另一個(gè)日期的前面還是后面
LocalDate tomorrow = LocalDate.of(2020, 1, 15); if(tommorow.isAfter(today)){ System.out.println("Tomorrow comes after today"); } LocalDate yesterday = today.minus(1, DAYS); if(yesterday.isBefore(today)){ System.out.println("Yesterday is day before today"); } Output: Tomorrow comes after today Yesterday is day before today
示例 12 在 Java 8 中處理不同的時(shí)區(qū)
// Date and time with timezone in Java 8 ZoneId america = ZoneId.of("America/New_York"); LocalDateTime localtDateAndTime = LocalDateTime.now(); ZonedDateTime dateAndTimeInNewYork = ZonedDateTime.of(localtDateAndTime, america ); System.out.println("Current date and time in a particular timezone : " + dateAndTimeInNewYork); Output : Current date and time in a particular timezone : 2020-01-14T16:33:33.373-05:00[America/New_York] Exception in thread "main" java.time.zone.ZoneRulesException: Unknown time-zone ID: ASIA/Tokyo at java.time.zone.ZoneRulesProvider.getProvider(ZoneRulesProvider.java:272) at java.time.zone.ZoneRulesProvider.getRules(ZoneRulesProvider.java:227) at java.time.ZoneRegion.ofId(ZoneRegion.java:120) at java.time.ZoneId.of(ZoneId.java:403) at java.time.ZoneId.of(ZoneId.java:351)
示例 13 如何表示固定的日期,比如信用卡過期時(shí)間
YearMonth currentYearMonth = YearMonth.now(); System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth()); YearMonth creditCardExpiry = YearMonth.of(2018, Month.FEBRUARY); System.out.printf("Your credit card expires on %s %n", creditCardExpiry); Output: Days in month year 2020-01: 31 Your credit card expires on 2018-02
示例 14 如何在 Java 8 中檢查閏年
if(today.isLeapYear()){ System.out.println("This year is Leap year"); }else { System.out.println("2020 is not a Leap year"); } Output: 2020 is not a Leap year
示例 15 兩個(gè)日期之間包含多少天,多少個(gè)月
LocalDate java8Release = LocalDate.of(2020, Month.MARCH, 14); Period periodToNextJavaRelease = Period.between(today, java8Release); System.out.println("Months left between today and Java 8 release : " + periodToNextJavaRelease.getMonths() ); Output: Months left between today and Java 8 release : 2
示例 16 帶時(shí)區(qū)偏移量的日期與時(shí)間
LocalDateTime datetime = LocalDateTime.of(2020, Month.JANUARY, 14, 19, 30); ZoneOffset offset = ZoneOffset.of("+05:30"); OffsetDateTime date = OffsetDateTime.of(datetime, offset); System.out.println("Date and Time with timezone offset in Java : " + date); Output : Date and Time with timezone offset in Java : 2020-01-14T19:30+05:30
示例 17 在 Java 8 中如何獲取當(dāng)前時(shí)間戳
Instant timestamp = Instant.now(); System.out.println("What is value of this instant " + timestamp); Output : What is value of this instant 2020-01-14T08:33:33.379Z
示例 18 如何在 Java 8 中使用預(yù)定義的格式器來對日期進(jìn)行解析 / 格式化
String dayAfterTommorrow = "20200116"; LocalDate formatted = LocalDate.parse(dayAfterTommorrow, DateTimeFormatter.BASIC_ISO_DATE); System.out.printf("Date generated from String %s is %s %n", dayAfterTommorrow, formatted); Output : Date generated from String 20200116 is 2020-01-16
示例 19 如何在 Java 中使用自定義的格式器來解析日期
String goodFriday = "Apr 18 2020"; try { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd yyyy"); LocalDate holiday = LocalDate.parse(goodFriday, formatter); System.out.printf("Successfully parsed String %s, date is %s%n", goodFriday, holiday); } catch (DateTimeParseException ex) { System.out.printf("%s is not parsable!%n", goodFriday); ex.printStackTrace(); } Output : Successfully parsed String Apr 18 2020, date is 2020-04-18
示例 20 如何在 Java 8 中對日期進(jìn)行格式化,轉(zhuǎn)換成字符串
LocalDateTime arrivalDate = LocalDateTime.now(); try { DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM dd yyyy hh:mm a"); String landing = arrivalDate.format(format); System.out.printf("Arriving at : %s %n", landing); } catch (DateTimeException ex) { System.out.printf("%s can't be formatted!%n", arrivalDate); ex.printStackTrace(); } Output : Arriving at : Jan 14 2020 04:33 PM
示例 21獲取時(shí)間戳秒和毫秒
Instant ins= Instant.now(); System.out.println("10位 秒"+ins.getEpochSecond()); System.out.println("13位 毫秒"+ins.toEpochMilli());
Java 8 中日期與時(shí)間 API 的幾個(gè)關(guān)鍵點(diǎn)
- 它提供了 javax.time.ZoneId 用來處理時(shí)區(qū)。
- 它提供了 LocalDate 與 LocalTime 類
- Java 8 中新的時(shí)間與日期 API 中的所有類都是不可變且線程安全的,這與之前的 Date 與 Calendar API 中的恰好相反,那里面像 java.util.Date 以及 SimpleDateFormat 這些關(guān)鍵的類都不是線程安全的。
- 新的時(shí)間與日期 API 中很重要的一點(diǎn)是它定義清楚了基本的時(shí)間與日期的概念,比方說,瞬時(shí)時(shí)間,持續(xù)時(shí)間,日期,時(shí)間,時(shí)區(qū)以及時(shí)間段。它們都是基于 ISO 日歷體系的。
- 每個(gè) Java 開發(fā)人員都應(yīng)該至少了解這套新的 API 中的這五個(gè)類:
- Instant 它代表的是時(shí)間戳,比如 2020-01-14T02:20:13.592Z,這可以從 java.time.Clock 類中獲取,像這樣: Instant current = Clock.system(ZoneId.of(“Asia/Tokyo”)).instant();
- LocalDate 它表示的是不帶時(shí)間的日期,比如 2020-01-14。它可以用來存儲(chǔ)生日,周年紀(jì)念日,入職日期等。
- LocalTime – 它表示的是不帶日期的時(shí)間
- LocalDateTime – 它包含了時(shí)間與日期,不過沒有帶時(shí)區(qū)的偏移量
- ZonedDateTime – 這是一個(gè)帶時(shí)區(qū)的完整時(shí)間,它根據(jù) UTC / 格林威治時(shí)間來進(jìn)行時(shí)區(qū)調(diào)整
- 這個(gè)庫的主包是 java.time,里面包含了代表日期,時(shí)間,瞬時(shí)以及持續(xù)時(shí)間的類。它有兩個(gè)子 package,一個(gè)是 java.time.foramt,這個(gè)是什么用途就很明顯了,還有一個(gè)是 java.time.temporal,它能從更低層面對各個(gè)字段進(jìn)行訪問。
- 時(shí)區(qū)指的是地球上共享同一標(biāo)準(zhǔn)時(shí)間的地區(qū)。每個(gè)時(shí)區(qū)都有一個(gè)唯一標(biāo)識符,同時(shí)還有一個(gè)地區(qū) / 城市 (Asia/Tokyo) 的格式以及從格林威治時(shí)間開始的一個(gè)偏移時(shí)間。比如說,東京的偏移時(shí)間就是 + 09:00。
- OffsetDateTime 類實(shí)際上包含了 LocalDateTime 與 ZoneOffset。它用來表示一個(gè)包含格林威治時(shí)間偏移量(+/- 小時(shí):分,比如 + 06:00 或者 -08:00)的完整的日期(年月日)及時(shí)間(時(shí)分秒,納秒)。
- DateTimeFormatter 類用于在 Java 中進(jìn)行日期的格式化與解析。與 SimpleDateFormat 不同,它是不可變且線程安全的,如果需要的話,可以賦值給一個(gè)靜態(tài)變量。DateTimeFormatter 類提供了許多預(yù)定義的格式器,你也可以自定義自己想要的格式。當(dāng)然了,根據(jù)約定,它還有一個(gè) parse() 方法是用于將字符串轉(zhuǎn)換成日期的,如果轉(zhuǎn)換期間出現(xiàn)任何錯(cuò)誤,它會(huì)拋出 DateTimeParseException 異常。類似的,DateFormatter 類也有一個(gè)用于格式化日期的 format() 方法,它出錯(cuò)的話則會(huì)拋出 DateTimeException 異常。
- 再說一句,“MMM d yyyy”與 “MMm dd yyyy” 這兩個(gè)日期格式也略有不同,前者能識別出”Jan 2 2020″與”Jan 14 2020″這兩個(gè)串,而后者如果傳進(jìn)來的是”Jan 2 2020″則會(huì)報(bào)錯(cuò),因?yàn)樗谕路萏巶鬟M(jìn)來的是兩個(gè)字符。為了解決這個(gè)問題,在天為個(gè)位數(shù)的情況下,你得在前面補(bǔ) 0,比如”Jan 2 2020″應(yīng)該改為”Jan 02 2020″。
總結(jié)
到此這篇關(guān)于Java 8新時(shí)間日期庫java.time使用的文章就介紹到這了,更多相關(guān)Java 8新時(shí)間日期庫java.time內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- java 運(yùn)行報(bào)錯(cuò)has been compiled by a more recent version of the Java Runtime
- Java8的DateTimeFormatter與SimpleDateFormat的區(qū)別詳解
- Java8中LocalDateTime與時(shí)間戳timestamp的互相轉(zhuǎn)換
- Java中joda日期格式化工具的使用示例
- 史上最全Java8日期時(shí)間工具類(分享)
- java處理日期的工具類DateUtil
- java實(shí)現(xiàn)的日期時(shí)間轉(zhuǎn)換工具類完整示例
- java常用工具類 Date日期、Mail郵件工具類
- java日期時(shí)間操作工具類
- java字符串與日期類型轉(zhuǎn)換的工具類
- java時(shí)間戳與日期相互轉(zhuǎn)換工具詳解
- Java 日期時(shí)間工具包–java.time的使用
相關(guān)文章
java中的final關(guān)鍵字詳解及實(shí)例
這篇文章主要介紹了 java中的final關(guān)鍵字詳解及實(shí)例的相關(guān)資料,需要的朋友可以參考下2017-03-03關(guān)于log4j漏洞修復(fù)解決方案及源碼編譯
Log4j?是Apache為Java提供的日志管理工具。他與System.out.println()的作用相似,用來跟蹤、調(diào)試、維護(hù)程序。這篇文章主要介紹了關(guān)于log4j漏洞修復(fù)解決方案及源碼編譯,需要的朋友可以參考下2021-12-12SpringBoot實(shí)現(xiàn)緩存組件配置動(dòng)態(tài)切換的步驟詳解
現(xiàn)在有多個(gè)springboot項(xiàng)目,但是不同的項(xiàng)目中使用的緩存組件是不一樣的,有的項(xiàng)目使用redis,有的項(xiàng)目使用ctgcache,現(xiàn)在需要用同一套代碼通過配置開關(guān),在不同的項(xiàng)目中切換這兩種緩存,本文介紹了SpringBoot實(shí)現(xiàn)緩存組件配置動(dòng)態(tài)切換的步驟,需要的朋友可以參考下2024-07-07高可用架構(gòu)etcd選主故障主備秒級切換實(shí)現(xiàn)
這篇文章主要為大家介紹了高可用架構(gòu)etcd選主故障主備秒級切換的實(shí)現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-02-02Java?SE判斷兩個(gè)文件內(nèi)容是否相同的多種方法代碼
昨天因?yàn)橐獛蛶熜值拿λ钥戳艘幌氯绾闻袛鄡蓚€(gè)文件內(nèi)容是否相同,這里給大家總結(jié)下,這篇文章主要給大家介紹了關(guān)于Java?SE判斷兩個(gè)文件內(nèi)容是否相同的多種方法,需要的朋友可以參考下2023-11-11