目錄
前言
Instant(時間戳)類
LocalData(日期)類
LocalTime(時間)類
LocalDataTime(日期時間)類
Duration(時間間隔)類
Period(日期間隔)類
Clock(獲取時區)類
前言
在開發中經常需要處理日期和時間,Java提供了一套專門用于處理日期時間的API,在日期時間類中了包含LocalDate類、LocalTime類、Instant類、Duration類以及Period類等,這些類都包含在java.time包中。
類的名稱 | 功能描述 |
Instant | 表示時刻,代表的是時間戳 |
LocalDate | 不包含具體時間的日期 |
LocalTime | 不含日期的時間 |
LocalDateTime | 包含了日期及時間 |
Duration | 基于時間的值測量時間量 |
Period | 計算日期時間差異,只能精確到年月日 |
Clock | 時鐘系統,用于查找當前時刻 |
Instant(時間戳)類
Instant 類代表的是某個時間。其內部是由兩個Long字段組成,
-
第一部分是保存自標準Java計算時代(即1970年1月1日開始)至當前時間的秒數,即時間戳(Timestamp)。該時間戳表示從參考時間點開始經過的秒數。
-
第二部分是保存納秒數。納秒是時間的更精細單位,表示每秒鐘的十億分之一。
常用方法
now()
:使用系統時鐘獲取當前瞬時。now(Clock clock)
:使用指定時鐘獲取當前瞬時。ofEpochSecond(long epochSecond)
:使用自標準Java計算時代開始的秒數獲得一個Instant
實例。ofEpochMilli(long epochMilli)
:使用自標準Java計算時代開始的毫秒數獲得一個Instant
實例。getEpochSecond()
:獲取時間戳的秒數部分。getNano()
:獲取時間戳的納秒數部分。parse(CharSequence text)
:將表示時間的字符串轉換為對應的Instant
對象。from(TemporalAccessor tenporal)
:從時間對象獲取一個Instant
的實例。plusSeconds(long seconds)
?和?plusMillis(long millis)
:在時間戳的基礎上增加指定的秒數或毫秒數。minusSeconds()
?和?minusMillis()
:在時間戳的基礎上減去指定的秒數或毫秒數。isBefore()
?和?isAfter()
?方法:比較兩個時間戳的先后順序。
示例代碼:
import java.time.Clock;
import java.time.Instant;public class InstantExample {public static void main(String[] args) {// 獲取當前時間的瞬時實例Instant now = Instant.now();System.out.println("當前時間:" + now);// 使用指定時鐘獲取當前時間的瞬時實例Clock clock = Clock.systemUTC();Instant nowWithClock = Instant.now(clock);System.out.println("當前時間(使用指定時鐘):" + nowWithClock);// 使用從自標準Java計算時代開始的秒數創建Instant實例 Instant epochSecondInstant = Instant.ofEpochSecond(1234567890);System.out.println("自1970年1月1日起的秒數對應的時間:" + epochSecondInstant);// 使用從自標準Java計算時代開始的毫秒數創建Instant實例Instant epochMilliInstant = Instant.ofEpochMilli(1627368000000L);System.out.println("自1970年1月1日起的毫秒數對應的時間:" + epochMilliInstant);// 獲取時間戳的秒數部分long seconds = now.getEpochSecond();System.out.println("時間戳的秒數部分:" + seconds);// 獲取時間戳的納秒數部分int nanos = now.getNano();System.out.println("時間戳的納秒數部分:" + nanos);// 將表示時間的字符串轉換為Instant對象String timeString = "2023-08-14T10:30:00Z";Instant parsedInstant = Instant.parse(timeString);System.out.println("解析后的時間:" + parsedInstant);// 在時間戳的基礎上增加指定的秒數或毫秒數Instant plusSecondsInstant = now.plusSeconds(3600);Instant plusMillisInstant = now.plusMillis(1000);System.out.println("增加1小時后的時間:" + plusSecondsInstant);System.out.println("增加1秒后的時間:" + plusMillisInstant);// 在時間戳的基礎上減去指定的秒數或毫秒數Instant minusSecondsInstant = now.minusSeconds(1800);Instant minusMillisInstant = now.minusMillis(500);System.out.println("減去30分鐘后的時間:" + minusSecondsInstant);System.out.println("減去0.5秒后的時間:" + minusMillisInstant);// 比較兩個時間戳的先后順序Instant earlierInstant = Instant.parse("2023-08-14T09:00:00Z");Instant laterInstant = Instant.parse("2023-08-14T11:00:00Z");boolean isBefore = earlierInstant.isBefore(laterInstant);boolean isAfter = earlierInstant.isAfter(laterInstant);System.out.println("earlierInstant是否在laterInstant之前:" + isBefore);System.out.println("earlierInstant是否在laterInstant之后:" + isAfter);}
}
運行結果:
當前時間:2023-08-14T09:41:00.027378100Z
當前時間(使用指定時鐘):2023-08-14T09:41:00.037343Z
自1970年1月1日起的秒數對應的時間:2009-02-13T23:31:30Z
自1970年1月1日起的毫秒數對應的時間:2021-07-27T06:40:00Z
時間戳的秒數部分:1692006060
時間戳的納秒數部分:27378100
解析后的時間:2023-08-14T10:30:00Z
增加1小時后的時間:2023-08-14T10:41:00.027378100Z
增加1秒后的時間:2023-08-14T09:41:01.027378100Z
減去30分鐘后的時間:2023-08-14T09:11:00.027378100Z
減去0.5秒后的時間:2023-08-14T09:40:59.527378100Z
earlierInstant是否在laterInstant之前:true
earlierInstant是否在laterInstant之后:false
LocalData(日期)類
LocalData類是Java 8引入的日期類,用于表示日期(年、月、日)信息。該類具有以下方法:
now()
:這是一個靜態方法,返回表示當前日期的LocalDate
對象。例如,LocalDate.now()
將返回表示今天日期的對象。of(int year, int month, int dayOfMonth)
:這是另一個靜態方法,通過指定年、月、日創建LocalDate
對象。參數year
表示年份,month
表示月份(1到12之間),dayOfMonth
表示月份中的某一天。format(DateTimeFormatter formatter)
:該方法可將LocalDate
對象按照指定的格式轉換為字符串表示。需要傳入一個DateTimeFormatter
對象,可以使用預定義的格式或自定義格式。例如,date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
將返回帶有“年-月-日”格式的日期字符串。plusYears(long years)
/minusYears(long years)
:這些方法用于在現有的LocalDate
對象上增加或減少指定的年數。參數years
表示要增加或減少的年數。plusMonths(long months)
/minusMonths(long months)
:與上述方法類似,這些方法用于在現有的LocalDate
對象上增加或減少指定的月數。plusDays(long days)
/minusDays(long days)
:這些方法用于在現有的LocalDate
對象上增加或減少指定的天數。isBefore(LocalDate other)
/isAfter(LocalDate other)
:這兩個方法用于比較兩個LocalDate
對象的先后順序。isBefore()
方法返回一個布爾值,表示該日期是否在參數日期之前;isAfter()
方法返回一個布爾值,表示該日期是否在參數日期之后。getYear()
/getMonthValue()
/getDayOfMonth()
:這些方法用于獲取LocalDate
對象的年、月、日信息。isLeapYear():
用于判斷指定年份是否為閏年。
示例代碼:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;public class myclass {public static void main(String[] args) {// 獲取當前日期LocalDate currentDate = LocalDate.now();System.out.println("當前日期:" + currentDate);// 創建指定日期LocalDate customDate = LocalDate.of(2023, 8, 14);System.out.println("自定義日期:" + customDate);// 格式化日期為字符串String formattedDate = customDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));System.out.println("格式化后的日期:" + formattedDate);// 增減年份LocalDate futureDate = customDate.plusYears(2);System.out.println("增加兩年后的日期:" + futureDate);// 判斷日期先后boolean isBefore = customDate.isBefore(currentDate);boolean isAfter = customDate.isAfter(currentDate);System.out.println("自定義日期是否在當前日期之前:" + isBefore);System.out.println("自定義日期是否在當前日期之后:" + isAfter);// 獲取年、月、日int year = customDate.getYear();int month = customDate.getMonthValue();int dayOfMonth = customDate.getDayOfMonth();System.out.println("年:" + year);System.out.println("月:" + month);System.out.println("日:" + dayOfMonth);// 判斷閏年boolean isLeapYear = customDate.isLeapYear();System.out.println("自定義日期所在年份是否為閏年:" + isLeapYear);}
}
運行結果:
當前日期:2023-08-14
自定義日期:2023-08-14
格式化后的日期:2023-08-14
增加兩年后的日期:2025-08-14
自定義日期是否在當前日期之前:false
自定義日期是否在當前日期之后:false
年:2023
月:8
日:14
自定義日期所在年份是否為閏年:false
LocalTime(時間)類
LocalTime類用來表示時間,通常表示的是小時分鐘秒。與LocalData類一樣,該類不能代表時間線上的即時信息,只是時間的描述。在LocalTime類中提供了獲取時間對象的方法,與LocalData用法類似。
同時LocalTime類也提供了與日期類相對應的時間格式化、增減時分秒等常用方法,這些方法與LocalData(日期)類相對應,這里我們不再詳細列舉。
示例代碼:
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;public class LocalTimeExample {public static void main(String[] args) {// 獲取當前時間LocalTime currentTime = LocalTime.now();System.out.println("當前時間:" + currentTime);// 創建指定時間LocalTime customTime = LocalTime.of(12, 30, 45);System.out.println("自定義時間:" + customTime);// 格式化時間為字符串String formattedTime = customTime.format(DateTimeFormatter.ofPattern("HH:mm:ss"));System.out.println("格式化后的時間:" + formattedTime);// 增減小時數LocalTime futureTime = customTime.plusHours(2);System.out.println("增加兩小時后的時間:" + futureTime);// 判斷時間先后boolean isBefore = customTime.isBefore(currentTime);boolean isAfter = customTime.isAfter(currentTime);System.out.println("自定義時間是否在當前時間之前:" + isBefore);System.out.println("自定義時間是否在當前時間之后:" + isAfter);// 獲取小時、分鐘、秒int hour = customTime.getHour();int minute = customTime.getMinute();int second = customTime.getSecond();System.out.println("小時:" + hour);System.out.println("分鐘:" + minute);System.out.println("秒:" + second);}
}
運行結果:
當前時間:18:04:40.272290700
自定義時間:12:30:45
格式化后的時間:12:30:45
增加兩小時后的時間:14:30:45
自定義時間是否在當前時間之前:true
自定義時間是否在當前時間之后:false
小時:12
分鐘:30
秒:45
LocalDataTime(日期時間)類
LocalDataTime類是日期(LocalDate)類與時間(LocalTime)類的綜合,它即包含日期也包含時間,通過查看API可以知道,LocalDataTime類中的方法包含了LocalData類與LocalTime類的方法。
需要注意的是,LocalDateTime默認的格式是 2020-02-29T21:23:26.774,這可能與我們經常使用的格式不太符合,所以它經常和DateTimeFormatter一起使用指定格式,除了LocalData與LocalTime類中的方法,額外提供了轉換的方法。
以下是一些LocalDateTime類常用的方法:
- now():靜態方法,返回當前日期和時間的LocalDateTime對象。
- of(int year, int month, int dayOfMonth, int hour, int minute) / of(int year, int month, int dayOfMonth, int hour, int minute, int second):靜態方法,通過指定年、月、日、小時、分鐘以及秒數(可選)創建LocalDateTime對象。
- parse(CharSequence text):靜態方法,將字符串解析為LocalDateTime對象。
- format(DateTimeFormatter formatter):將LocalDateTime對象按照指定格式轉換為字符串表示。
- toLocalDate():獲取LocalDateTime對象的日期部分,返回LocalDate對象。
- toLocalTime():獲取LocalDateTime對象的時間部分,返回LocalTime對象。
- plusYears(long years) / minusYears(long years):在現有的LocalDateTime對象上增加或減少指定年數。
- plusMonths(long months) / minusMonths(long months):在現有的LocalDateTime對象上增加或減少指定月數。
- plusDays(long days) / minusDays(long days):在現有的LocalDateTime對象上增加或減少指定天數。
- plusHours(long hours) / minusHours(long hours):在現有的LocalDateTime對象上增加或減少指定小時數。
- plusMinutes(long minutes) / minusMinutes(long minutes):在現有的LocalDateTime對象上增加或減少指定分鐘數。
- plusSeconds(long seconds) / minusSeconds(long seconds):在現有的LocalDateTime對象上增加或減少指定秒數。
- getYear() / getMonthValue() / getDayOfMonth():獲取LocalDateTime對象的年、月、日信息。
示例代碼:?
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;public class myclass {public static void main(String[] args) {// 獲取當前日期和時間LocalDateTime currentDateTime = LocalDateTime.now();System.out.println("當前日期和時間:" + currentDateTime);// 創建指定的日期和時間LocalDateTime customDateTime = LocalDateTime.of(2023, 8, 14, 12, 30);System.out.println("自定義日期和時間:" + customDateTime);// 格式化日期時間為字符串String formattedDateTime = customDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));System.out.println("格式化后的日期和時間:" + formattedDateTime);// 增減年數、月數、天數、小時數、分鐘數、秒數LocalDateTime futureDateTime = customDateTime.plusYears(1).minusMonths(2).plusDays(15).minusHours(3).plusMinutes(10).plusSeconds(30);System.out.println("操作后的日期和時間:" + futureDateTime);// 獲取日期和時間部分LocalDate datePart = customDateTime.toLocalDate();LocalTime timePart = customDateTime.toLocalTime();System.out.println("日期部分:" + datePart);System.out.println("時間部分:" + timePart);// 獲取年、月、日信息int year = customDateTime.getYear();int month = customDateTime.getMonthValue();int dayOfMonth = customDateTime.getDayOfMonth();System.out.println("年:" + year);System.out.println("月:" + month);System.out.println("日:" + dayOfMonth);}
}
運行結果:
當前日期和時間:2023-08-14T18:09:24.472147600
自定義日期和時間:2023-08-14T12:30
格式化后的日期和時間:2023-08-14 12:30:00
操作后的日期和時間:2024-06-29T09:40:30
日期部分:2023-08-14
時間部分:12:30
年:2023
月:8
日:14
Duration(時間間隔)類
Duration類是Java 8引入的一個用于表示時間間隔的類。它可用于計算兩個時間點之間的差異,以及在不同單位(如秒、分鐘、小時等)之間進行轉換。
以下是一些Duration類常用的方法:
- ofDays(long days) / ofHours(long hours) / ofMinutes(long minutes):靜態方法,創建一個持續時間,表示指定的天數、小時數或分鐘數。
- ofSeconds(long seconds) / ofMillis(long milliseconds) / ofNanos(long nanos):靜態方法,創建一個持續時間,表示指定的秒數、毫秒數或納秒數。
- between(Temporal startInclusive, Temporal endExclusive):靜態方法,創建一個持續時間,表示從起始時間到結束時間之間的差異。
- plus(Duration duration) / minus(Duration duration):在現有的Duration對象上增加或減少另一個Duration對象的持續時間。
- toDays() / toHours() / toMinutes():將持續時間轉換為對應的天數、小時數或分鐘數。
- toSeconds() / toMillis() / toNanos():將持續時間轉換為對應的秒數、毫秒數或納秒數。
- getSeconds() / getNano():獲取持續時間中的秒數和納秒數。
- isNegative() / isZero():判斷持續時間是否為負值或零值。
示例代碼:??
import java.time.Duration;public class myclass {public static void main(String[] args) {// 創建一個持續時間,表示5小時30分鐘15秒Duration duration1 = Duration.ofHours(5).plusMinutes(30).plusSeconds(15);System.out.println("Duration 1: " + duration1); // 輸出:PT5H30M15S// 創建一個持續時間,表示1分鐘Duration duration2 = Duration.ofMinutes(1);System.out.println("Duration 2: " + duration2); // 輸出:PT1M// 計算兩個持續時間之間的差異Duration difference = duration1.minus(duration2);System.out.println("Difference: " + difference); // 輸出:PT5H29M15S// 獲取持續時間的小時數、分鐘數和秒數long hours = difference.toHours();long minutes = difference.toMinutesPart();long seconds = difference.toSecondsPart();System.out.println("Hours: " + hours); // 輸出:5System.out.println("Minutes: " + minutes); // 輸出:29System.out.println("Seconds: " + seconds); // 輸出:15// 判斷持續時間是否為負值或零值boolean isNegative = difference.isNegative();boolean isZero = difference.isZero();System.out.println("是負的? " + isNegative); // 輸出:falseSystem.out.println("是零嗎? " + isZero); // 輸出:false}
}
Period(日期間隔)類
?Period主要用于計算兩個日期的間隔,與Duration相同,也是通過between計算日期間隔,并提供了獲取年月日的三個常用方法,分別是 getYears()、getMonths()和getDays()。
示例代碼:??
import java.time.LocalDate;
import java.time.Period;public class myclass {public static void main(String[] args) {// 創建兩個日期LocalDate startDate = LocalDate.of(2023, 1, 1);LocalDate endDate = LocalDate.of(2023, 4, 30);// 計算日期之間的差異Period period = Period.between(startDate, endDate);System.out.println("日期間隔: " + period); // 輸出:P3M29D// 獲取年、月、日的差異int years = period.getYears();int months = period.getMonths();int days = period.getDays();System.out.println("年: " + years); // 輸出:0System.out.println("月: " + months); // 輸出:3System.out.println("日: " + days); // 輸出:29// 添加日期間隔到指定日期LocalDate newDate = startDate.plus(period);System.out.println("新日期: " + newDate); // 輸出:2023-04-30// 判斷日期間隔是否為負值或零值boolean isNegative = period.isNegative();boolean isZero = period.isZero();System.out.println("是否為負值? " + isNegative); // 輸出:falseSystem.out.println("是否為零值? " + isZero); // 輸出:false}
}
Clock(獲取時區)類
Clock
類是Java中用于獲取當前時間、日期和時區信息的抽象類。它提供了一種通用的方式來訪問系統時鐘,并以不同的時區獲取當前時間。
- systemDefaultZone():靜態方法,返回使用系統默認時區的系統時鐘。
- systemUTC():靜態方法,返回使用協調世界時(UTC)的系統時鐘。
- tick(Clock fixedClock, Duration tickDuration):靜態方法,返回一個包裝了指定時鐘的"滴答"時鐘,每次前進指定的時長。
- fixed(Instant fixedInstant, ZoneId zone):靜態方法,返回一個固定的時鐘,始終返回指定的瞬間和時區。
- offset(Clock baseClock, Duration offsetDuration):靜態方法,返回一個相對于基準時鐘偏移指定持續時間的時鐘。
- millis():實例方法,返回從1970年1月1日午夜開始的毫秒數。
- instant():實例方法,返回當前時鐘的當前瞬間。
- getZone():實例方法,返回時鐘的時區信息。
示例代碼:???
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;public class myclass {public static void main(String[] args) {// 獲取系統默認時區的時鐘Clock systemDefaultClock = Clock.systemDefaultZone();System.out.println("系統默認時鐘:" + systemDefaultClock);// 獲取使用協調世界時(UTC)的系統時鐘Clock systemUTCClock = Clock.systemUTC();System.out.println("系統UTC時鐘:" + systemUTCClock);// 創建一個滴答時鐘,每次前進1秒鐘Clock tickClock = Clock.tick(systemDefaultClock, Duration.ofSeconds(1));System.out.println("滴答時鐘:" + tickClock);// 創建一個固定的時鐘,始終返回指定的瞬間和時區Instant fixedInstant = Instant.parse("2022-01-01T00:00:00Z");ZoneId fixedZone = ZoneId.of("Asia/Shanghai");//亞洲/上海Clock fixedClock = Clock.fixed(fixedInstant, fixedZone);System.out.println("固定時鐘:" + fixedClock);// 創建一個相對于基準時鐘偏移10秒鐘的時鐘Clock baseClock = Clock.systemDefaultZone();Duration offsetDuration = Duration.ofSeconds(10);Clock offsetClock = Clock.offset(baseClock, offsetDuration);System.out.println("偏移時鐘:" + offsetClock);// 獲取當前時鐘的毫秒數long millis = systemDefaultClock.millis();System.out.println("毫秒數:" + millis);// 獲取當前時鐘的當前瞬間Instant instant = systemDefaultClock.instant();System.out.println("當前瞬間:" + instant);// 獲取當前時鐘的時區信息ZoneId zone = systemDefaultClock.getZone();System.out.println("時區:" + zone);}
}