Java日期類詳解(最新推薦)
在 Java 中,處理日期和時間的類隨著版本的發(fā)展有不同的體系。早期版本主要使用 java.util.Date
、java.util.Calendar
等類,Java 8 及以后引入了新的日期和時間 API(JSR 310),包含在 java.time
包中。
甲骨文官方文檔
Overview (Java SE 21 & JDK 21)
JDK中文文檔。https://java.cunzaima.cn/jdk21/doc-zh/api/index.html
舊的日期時間API
1. java.util.Date
- 概述:
Date
類表示特定的瞬間,精確到毫秒。不過它的很多方法在 Java 1.1 之后已經(jīng)被棄用,因為其設(shè)計存在一些問題,比如線程不安全、缺乏時區(qū)支持等。 - 常用方法
Date()
:創(chuàng)建一個表示當(dāng)前時間的Date
對象。Date(long date)
:根據(jù)給定的毫秒數(shù)創(chuàng)建Date
對象,該毫秒數(shù)是從 1970 年 1 月 1 日 00:00:00 GMT 開始計算的。getTime()
:返回自 1970 年 1 月 1 日 00:00:00 GMT 以來此Date
對象表示的毫秒數(shù)。equals(Object obj)
:比較兩個Date
對象是否相等。
import java.util.Date; public class DateExample { public static void main(String[] args) { // 創(chuàng)建表示當(dāng)前時間的 Date 對象 Date currentDate = new Date(); System.out.println("當(dāng)前時間: " + currentDate); // 根據(jù)毫秒數(shù)創(chuàng)建 Date 對象 long milliseconds = 1609459200000L; Date specificDate = new Date(milliseconds); System.out.println("指定時間: " + specificDate); // 獲取毫秒數(shù) long timeInMillis = currentDate.getTime(); System.out.println("當(dāng)前時間的毫秒數(shù): " + timeInMillis); // 比較兩個 Date 對象 boolean isEqual = currentDate.equals(specificDate); System.out.println("兩個日期是否相等: " + isEqual); } }
2. java.util.Calendar
- 概述:
Calendar
是一個抽象類,用于在 Java 中進(jìn)行日期和時間的計算。它提供了一些方法來獲取和設(shè)置年、月、日、時、分、秒等信息,并且支持時區(qū)和本地化。 - 常用方法
Calendar.getInstance()
:獲取一個Calendar
實例,該實例使用默認(rèn)時區(qū)和語言環(huán)境。get(int field)
:獲取指定字段的值,例如Calendar.YEAR
、Calendar.MONTH
等。set(int field, int value)
:設(shè)置指定字段的值。add(int field, int amount)
:對指定字段進(jìn)行加減操作。
import java.util.Calendar; public class CalendarExample { public static void main(String[] args) { // 獲取 Calendar 實例 Calendar calendar = Calendar.getInstance(); // 獲取年、月、日 int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; // 月份從 0 開始,所以要加 1 int day = calendar.get(Calendar.DAY_OF_MONTH); System.out.println("當(dāng)前日期: " + year + "-" + month + "-" + day); // 設(shè)置日期 calendar.set(Calendar.YEAR, 2025); calendar.set(Calendar.MONTH, Calendar.JUNE); calendar.set(Calendar.DAY_OF_MONTH, 15); System.out.println("設(shè)置后的日期: " + calendar.getTime()); // 日期加減操作 calendar.add(Calendar.DAY_OF_MONTH, 5); System.out.println("加 5 天后的日期: " + calendar.getTime() +"\t" + calendar.getTime().getTime()+"\t"+ calendar.getTimeInMillis() +"\t" + calendar.getTimeZone().getOffset(calendar.getTimeInMillis())); // 設(shè)置時區(qū) TimeZone timeZone = TimeZone.getTimeZone("America/New_York"); calendar.setTimeZone(timeZone); System.out.println("美國紐約的日期: " + calendar.getTime() +"\t" + calendar.getTime().getTime() +"\t"+ calendar.getTimeInMillis() +"\t" + calendar.getTimeZone().getOffset(calendar.getTimeInMillis())); } }
SimpleDateFormat
:用于將Date
對象格式化為指定的字符串格式,或者將字符串解析為Date
對象。它通過模式字符串來定義日期和時間的格式,常用的模式字符有:
y
:年,如yyyy
表示四位年份,yy
表示兩位年份。M
:月,MM
表示兩位數(shù)字的月份,MMM
表示月份的縮寫(如 Jan、Feb 等),MMMM
表示月份的全稱。d
:日,dd
表示兩位數(shù)字的日。H
:小時(24 小時制),HH
表示兩位數(shù)字的小時。h
:小時(12 小時制)。m
:分鐘,mm
表示兩位數(shù)字的分鐘。s
:秒,ss
表示兩位數(shù)字的秒。S
:毫秒。z
:時區(qū),如CST
。
例如,SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
可以將Date
對象格式化為2024-05-08 14:34:56
這樣的字符串。
java.util.Calendar
:Calendar
類主要用于對日期和時間進(jìn)行操作和計算,它本身沒有直接的日期格式表示。但可以通過SimpleDateFormat
將Calendar
對象轉(zhuǎn)換為指定格式的字符串,例如:
Calendar calendar = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateStr = sdf.format(calendar.getTime()); String dateString = "2024-10-01 14:30:00"; try { Date date = sdf.parse(dateString); System.out.println("解析后的日期: " + date); } catch (ParseException e) { System.out.println("解析日期時出錯: " + e.getMessage()); }
新的日期時間 API(Java 8+)
1. java.time.LocalDate
- 概述:
LocalDate
表示一個不可變的日期對象,只包含日期信息(年、月、日),不包含時間和時區(qū)信息。 - 常用方法
LocalDate.now()
:獲取當(dāng)前日期。LocalDate.of(int year, int month, int dayOfMonth)
:根據(jù)指定的年、月、日創(chuàng)建LocalDate
對象。getYear()
、getMonth()
、getDayOfMonth()
:獲取年、月、日信息。plusDays(long daysToAdd)
、minusDays(long daysToSubtract)
:進(jìn)行日期的加減操作。
import java.time.LocalDate; public class LocalDateExample { public static void main(String[] args) { // 獲取當(dāng)前日期 LocalDate currentDate = LocalDate.now(); System.out.println("當(dāng)前日期: " + currentDate); // 根據(jù)指定的年、月、日創(chuàng)建 LocalDate 對象 LocalDate specificDate = LocalDate.of(2025, 6, 15); System.out.println("指定日期: " + specificDate); // 獲取日期信息 int year = specificDate.getYear(); int month = specificDate.getMonthValue(); int day = specificDate.getDayOfMonth(); System.out.println("指定日期的年: " + year + ", 月: " + month + ", 日: " + day); // 日期加減操作 LocalDate newDate = specificDate.plusDays(5); System.out.println("加 5 天后的日期: " + newDate); } }
2. java.time.LocalTime
- 概述:
LocalTime
表示一個不可變的時間對象,只包含時間信息(時、分、秒、納秒),不包含日期和時區(qū)信息。 - 常用方法
LocalTime.now()
:獲取當(dāng)前時間。LocalTime.of(int hour, int minute)
:根據(jù)指定的時、分創(chuàng)建LocalTime
對象。getHour()
、getMinute()
、getSecond()
:獲取時、分、秒信息。plusHours(long hoursToAdd)
、minusMinutes(long minutesToSubtract)
:進(jìn)行時間的加減操作。
import java.time.LocalTime; public class LocalTimeExample { public static void main(String[] args) { // 獲取當(dāng)前時間 LocalTime currentTime = LocalTime.now(); System.out.println("當(dāng)前時間: " + currentTime); // 根據(jù)指定的時、分創(chuàng)建 LocalTime 對象 LocalTime specificTime = LocalTime.of(14, 30); System.out.println("指定時間: " + specificTime); // 獲取時間信息 int hour = specificTime.getHour(); int minute = specificTime.getMinute(); System.out.println("指定時間的時: " + hour + ", 分: " + minute); // 時間加減操作 LocalTime newTime = specificTime.plusHours(2); System.out.println("加 2 小時后的時間: " + newTime); } }
3. java.time.LocalDateTime
- 概述:
LocalDateTime
表示一個不可變的日期和時間對象,包含日期和時間信息(年、月、日、時、分、秒、納秒),不包含時區(qū)信息。 - 常用方法:結(jié)合了
LocalDate
和LocalTime
的方法,可進(jìn)行日期和時間的操作。
import java.time.LocalDateTime; public class LocalDateTimeExample { public static void main(String[] args) { // 獲取當(dāng)前日期和時間 LocalDateTime currentDateTime = LocalDateTime.now(); System.out.println("當(dāng)前日期和時間: " + currentDateTime); // 根據(jù)指定的日期和時間創(chuàng)建 LocalDateTime 對象 LocalDateTime specificDateTime = LocalDateTime.of(2025, 6, 15, 14, 30); System.out.println("指定日期和時間: " + specificDateTime); // 日期和時間加減操作 LocalDateTime newDateTime = specificDateTime.plusDays(2).plusHours(3); System.out.println("加 2 天 3 小時后的日期和時間: " + newDateTime); } }
4. java.time.ZonedDateTime
- 概述:
ZonedDateTime
表示一個帶時區(qū)的日期和時間對象,包含日期、時間和時區(qū)信息。 - 常用方法
ZonedDateTime.now()
:獲取當(dāng)前帶時區(qū)的日期和時間。ZonedDateTime.of(LocalDateTime localDateTime, ZoneId zone)
:根據(jù)LocalDateTime
和ZoneId
創(chuàng)建ZonedDateTime
對象。getZone()
:獲取時區(qū)信息。
import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; public class ZonedDateTimeExample { public static void main(String[] args) { // 獲取當(dāng)前帶時區(qū)的日期和時間 ZonedDateTime currentZonedDateTime = ZonedDateTime.now(); System.out.println("當(dāng)前帶時區(qū)的日期和時間: " + currentZonedDateTime); // 根據(jù) LocalDateTime 和 ZoneId 創(chuàng)建 ZonedDateTime 對象 LocalDateTime localDateTime = LocalDateTime.of(2025, 6, 15, 14, 30); ZoneId zoneId = ZoneId.of("Asia/Shanghai"); ZonedDateTime specificZonedDateTime = ZonedDateTime.of(localDateTime, zoneId); System.out.println("指定帶時區(qū)的日期和時間: " + specificZonedDateTime); // 獲取時區(qū)信息 ZoneId zone = specificZonedDateTime.getZone(); System.out.println("時區(qū): " + zone); } }
Instant
對象
now
方法:可以通過Instant.now()
獲取當(dāng)前時間的Instant
對象。例如,Instant instant = Instant.now();
,這將返回當(dāng)前時刻的Instant
,精確到納秒。
獲取時間戳
toEpochMilli
方法:Instant
提供了toEpochMilli
方法來獲取從 1970 年 1 月 1 日 00:00:00 UTC 到該Instant
所表示的時間點的毫秒數(shù)。例如,long millis = instant.toEpochMilli();
,可以將Instant
對象轉(zhuǎn)換為時間戳,方便與其他需要時間戳的系統(tǒng)或 API 進(jìn)行交互。getEpochSecond
方法:獲取從 1970 年 1 月 1 日 00:00:00 UTC 到該Instant
所表示的時間點的秒數(shù)。例如,long seconds = instant.getEpochSecond();
,如果需要以秒為單位獲取時間戳,可以使用該方法。
時間計算
Instant
可以進(jìn)行時間的加減運算,通過plus
和minus
方法來實現(xiàn)。例如,要獲取當(dāng)前時間 5 秒后的Instant
,可以使用Instant futureInstant = Instant.now().plusSeconds(5);
;要獲取 10 分鐘前的Instant
,可以使用Instant pastInstant = Instant.now().minusMinutes(10);
。
與其他日期時間類型的轉(zhuǎn)換
- 與
LocalDateTime
轉(zhuǎn)換:可以通過atZone
方法將Instant
轉(zhuǎn)換為指定時區(qū)的LocalDateTime
。例如,Instant instant = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
,這將把當(dāng)前的Instant
轉(zhuǎn)換為系統(tǒng)默認(rèn)時區(qū)的LocalDateTime
。反之,也可以通過toInstant
方法將LocalDateTime
轉(zhuǎn)換為Instant
,例如,LocalDateTime ldt = LocalDateTime.now(); Instant instant = ldt.toInstant(ZoneOffset.UTC);
,將當(dāng)前的LocalDateTime
轉(zhuǎn)換為 UTC 時區(qū)的Instant
。 - 與
ZonedDateTime
轉(zhuǎn)換:Instant
可以直接通過atZone
方法轉(zhuǎn)換為ZonedDateTime
,例如,Instant instant = Instant.now(); ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
,將當(dāng)前的Instant
轉(zhuǎn)換為系統(tǒng)默認(rèn)時區(qū)的ZonedDateTime
。而ZonedDateTime
也可以通過toInstant
方法轉(zhuǎn)換為Instant
,例如,ZonedDateTime zdt = ZonedDateTime.now(); Instant instant = zdt.toInstant();
。
DateTimeFormatter
java.time
包中的格式化類:新日期時間 API 提供了DateTimeFormatter
類來進(jìn)行日期和時間的格式化與解析。它的模式定義與SimpleDateFormat
有一些相似之處,但更加靈活和強大。常用的模式字符與SimpleDateFormat
類似,例如yyyy-MM-dd
、HH:mm:ss
等。LocalDate
、LocalTime
和LocalDateTime
:LocalDate
:表示日期,默認(rèn)格式為yyyy-MM-dd
,例如2024-05-08
??梢允褂?code>DateTimeFormatter進(jìn)行格式化,如
LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) //會將當(dāng)前日期格式化為08/05/2024。
LocalTime
:表示時間,默認(rèn)格式為HH:mm:ss.SSS
,例如14:34:56.123
。同樣可以通過DateTimeFormatter
進(jìn)行自定義格式化。LocalDateTime
:表示日期和時間,默認(rèn)格式為yyyy-MM-dd HH:mm:ss.SSS
,例如2024-05-08 14:34:56.123
。也能使用DateTimeFormatter
按照需求進(jìn)行格式化。
綜合案例:
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateTimeFormatterExample { public static void main(String[] args) { // 1. 通過模式字符串創(chuàng)建DateTimeFormatter DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 2. 格式化當(dāng)前日期時間 LocalDateTime now = LocalDateTime.now(); String formattedDateTime1 = formatter1.format(now); System.out.println("Formatted DateTime 1: " + formattedDateTime1); // 3. 使用預(yù)定義的格式創(chuàng)建DateTimeFormatter DateTimeFormatter formatter2 = DateTimeFormatter.ISO_LOCAL_DATE_TIME; String formattedDateTime2 = formatter2.format(now); System.out.println("Formatted DateTime 2: " + formattedDateTime2); // 4. 解析字符串為日期時間對象 String dateTimeStr = "2024-05-08 12:30:00"; LocalDateTime parsedDateTime = LocalDateTime.parse(dateTimeStr, formatter1); System.out.println("Parsed DateTime: " + parsedDateTime); // 5. 基于本地化創(chuàng)建DateTimeFormatter DateTimeFormatter formatter3 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL) .withLocale(Locale.CHINA); String formattedDateTime3 = formatter3.format(now); System.out.println("Formatted DateTime 3: " + formattedDateTime3); } }
Duration
Duration
類用于以秒和納秒的方式表示時間間隔,它主要處理基于時間(小時、分鐘、秒、納秒)的時間量,適用于處理諸如程序執(zhí)行時間、兩個時間點之間的時間差等場景。
創(chuàng)建 Duration
對象
Duration.between(Temporal startInclusive, Temporal endExclusive)
:根據(jù)兩個Temporal
對象(如LocalTime
、LocalDateTime
或Instant
)計算它們之間的時間間隔。
import java.time.Duration; import java.time.LocalTime; public class DurationExample { public static void main(String[] args) { LocalTime startTime = LocalTime.of(9, 0); LocalTime endTime = LocalTime.of(12, 30); Duration duration = Duration.between(startTime, endTime); System.out.println("時間間隔: " + duration); } }
Duration.of(long amount, TemporalUnit unit)
:通過指定數(shù)量和時間單位來創(chuàng)建Duration
對象。
Duration duration = Duration.of(2, java.time.temporal.ChronoUnit.HOURS); System.out.println("自定義時間間隔: " + duration);
獲取 Duration
中的值
可以使用 getSeconds()
方法獲取 Duration
中的總秒數(shù),使用 toHours()
、toMinutes()
等方法將其轉(zhuǎn)換為不同的時間單位
Duration duration = Duration.of(2, java.time.temporal.ChronoUnit.HOURS); System.out.println("總秒數(shù): " + duration.getSeconds()); System.out.println("總小時數(shù): " + duration.toHours());
對 Duration
進(jìn)行操作
Duration duration1 = Duration.of(1, java.time.temporal.ChronoUnit.HOURS); Duration duration2 = Duration.of(2, java.time.temporal.ChronoUnit.HOURS); Duration sumDuration = duration1.plus(duration2); Duration diffDuration = duration1.minus(duration2); System.out.println("相加后的間隔: " + sumDuration); System.out.println("相減后的間隔: " + diffDuration);
Period
Period
類用于以年、月、日的方式表示日期之間的間隔,它主要處理基于日期(年、月、日)的時間量,適用于處理諸如人的年齡、兩個事件之間的日期差等場景。
創(chuàng)建 Period
對象
Period.between(LocalDate startDate, LocalDate endDate)
:根據(jù)兩個 LocalDate
對象計算它們之間的日期間隔。
import java.time.LocalDate; import java.time.Period; public class PeriodExample { public static void main(String[] args) { LocalDate startDate = LocalDate.of(2020, 1, 1); LocalDate endDate = LocalDate.of(2023, 12, 31); Period period = Period.between(startDate, endDate); System.out.println("日期間隔: " + period); } }
Period.of(int years, int months, int days)
:通過指定年、月、日的值來創(chuàng)建 Period
對象。
Period period = Period.of(2, 3, 10); System.out.println("自定義日期間隔: " + period);
獲取 Period
中的值
可以使用 getYears()
、getMonths()
和 getDays()
方法分別獲取 Period
中的年、月、日部分
Period period = Period.of(2, 3, 10); System.out.println("年: " + period.getYears()); System.out.println("月: " + period.getMonths()); System.out.println("日: " + period.getDays());
對 Period
進(jìn)行操作
plus(Period other)
:將兩個Period
對象相加。minus(Period other)
:從當(dāng)前Period
中減去另一個Period
對象。Duration.between(Temporal startInclusive, Temporal endExclusive)
:根據(jù)兩個Temporal
對象(如LocalTime
、LocalDateTime
或Instant
)計算它們之間的時間間隔。Duration.of(long amount, TemporalUnit unit)
:通過指定數(shù)量和時間單位來創(chuàng)建Duration
對象。plus(Duration other)
:將兩個Duration
對象相加。minus(Duration other)
:從當(dāng)前Duration
中減去另一個Duration
對象。
總結(jié)
Period
用于處理基于日期的時間間隔,以年、月、日為單位。Duration
用于處理基于時間的時間間隔,以秒和納秒為單位。
新舊日期時間 API 對比
- 線程安全性:舊的
Date
和Calendar
類不是線程安全的,而新的日期時間 API 中的類都是不可變的,是線程安全的。 - 易用性:新的日期時間 API 提供了更豐富的方法和更清晰的設(shè)計,使用起來更加方便。
- 功能完整性:新的 API 對時區(qū)、日期計算等功能的支持更加完善。
到此這篇關(guān)于Java日期類的文章就介紹到這了,更多相關(guān)java日期類內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring Cloud zuul自定義統(tǒng)一異常處理實現(xiàn)方法
這篇文章主要介紹了Spring Cloud zuul自定義統(tǒng)一異常處理實現(xiàn),需要的朋友可以參考下2018-02-02將Java程序與數(shù)據(jù)庫進(jìn)行連接的操作方法
這篇文章主要介紹了將Java程序與數(shù)據(jù)庫進(jìn)行連接的操作方法,是Java入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-10-10springboot整合SSE技術(shù)開發(fā)小結(jié)
本文主要介紹了springboot整合SSE技術(shù)開發(fā)小結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-11-11