Java8不可或缺小幫手之日期應(yīng)用
jdk1.8后引入了新的日期時(shí)間處理API,相比傳統(tǒng)的date操作更加簡便,date中的SimpleDateFormat也是非線程安全的。
新的API是標(biāo)準(zhǔn)的ISO-8601日歷系統(tǒng),位于java.time包下,且所有類都是不可變類型、線程安全。
廢話不多說,開干。
1、獲取當(dāng)前日期時(shí)間
now() :靜態(tài)方法,根據(jù)當(dāng)前時(shí)間創(chuàng)建對(duì)象。例如:獲取當(dāng)前日期,當(dāng)前時(shí)間,當(dāng)前日期時(shí)間
//獲取當(dāng)前日期 LocalDate nowDate = LocalDate.now(); System.out.println("獲取當(dāng)前日期:"+nowDate); //獲取當(dāng)前時(shí)間 LocalTime nowTime = LocalTime.now(); System.out.println("獲取當(dāng)前時(shí)間:"+nowTime); //獲取當(dāng)前日期時(shí)間 LocalDateTime nowDateTime = LocalDateTime.now(); System.out.println("獲取當(dāng)前日期時(shí)間:"+nowDateTime);
輸出:
獲取當(dāng)前日期:2023-05-11
獲取當(dāng)前時(shí)間:11:10:10.453
獲取當(dāng)前日期時(shí)間:2023-05-11T11:10:10.454
2、日期時(shí)間格式化
DateTimeFormatter:靜態(tài)格式化類,提供了ofPattern,ofLocalizedDate,format等格式化方法。
方法 | 描述 |
---|---|
ofPattern(String pattern) | 格式化樣式定義,例如:yyyy-MM-dd等 |
format(TemporalAccessor temporal) | 執(zhí)行格式化,返回字符串類型的時(shí)間樣式,如:2023-05-11 |
ofLocalizedDate(FormatStyle dateStyle) | 返回特定區(qū)域的日期格式。FormatStyle提供了四種類型,分別是:FULL、LONG,SHORT、MEDIUM |
ofLocalizedTime(FormatStyle dateStyle) | 返回特定區(qū)域的時(shí)間格式。 |
ofLocalizedDateTime(FormatStyle dateStyle) | 返回特定區(qū)域的日期時(shí)間格式 |
注:在使用ofLocalizedTime,ofLocalizedDateTime中的FormatStyle.FULL,F(xiàn)ormatStyle.LONG時(shí)由于時(shí)區(qū)信息問題,通常不存儲(chǔ)在LocalTime,LocalDateTime對(duì)象中,因此會(huì)報(bào)取不到值的錯(cuò)誤。如:
private static final DateTimeFormatter TIME_DTF = DateTimeFormatter.ofPattern("hh:mm:ss"); private static final DateTimeFormatter DATE_DTF = DateTimeFormatter.ofPattern("yyyy-MM-dd"); private static final DateTimeFormatter DATE_TIME_DTF = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); //格式化 System.out.println("日期格式化:" + DATE_DTF.format(nowDate)); System.out.println("時(shí)間格式化:" + TIME_DTF.format(nowTime)); System.out.println("日期時(shí)間格式化:" + DATE_TIME_DTF.format(nowDateTime)); System.out.println("日期樣式:" + DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).format(nowDate)); System.out.println("日期樣式:" + DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).format(nowDate)); System.out.println("日期樣式:" + DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).format(nowDate)); System.out.println("日期樣式:" + DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).format(nowDate)); //System.out.println("時(shí)間樣式:" + DateTimeFormatter.ofLocalizedTime(FormatStyle.FULL).format(LocalTime.now())); System.out.println("時(shí)間樣式:" + nowTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM))); // System.out.println("時(shí)間樣式:" + nowTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.LONG))); System.out.println("時(shí)間樣式:" + nowTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT))); System.out.println("日期時(shí)間樣式:" + DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).format(nowDateTime));
輸出:
日期格式化:2023-05-11
時(shí)間格式化:11:43:48
日期時(shí)間格式化:2023-05-11 11:43:48
日期樣式:2023年5月11日 星期四
日期樣式:2023-5-11
日期樣式:23-5-11
日期樣式:2023年5月11日
時(shí)間樣式:11:43:48
時(shí)間樣式:上午11:43
日期時(shí)間樣式:2023-5-11 11:43:48
3、獲取日期的年月日
在Date中獲取月份是從0開始的,因此真正的月份是需要加1的。而LocalDate提供的方法則不需要。
- getYear() :獲取年份,返回int,
- getMonthValue() :獲取月份值,相當(dāng)于是getMonth().getValue()。
- getMonth() :獲取的是月份枚舉類型,存儲(chǔ)的是英文的月份,可以通過getValue()獲取int的月份
- getDayOfMonth() :獲取月份中第幾天,
- getDayOfYear() :獲取當(dāng)前日期在一年中的第幾天。
- getDayOfWeek() :獲取星期,返回DayOfWeek枚舉,保存英文星期,通過getValue()獲取數(shù)字星期幾。
//獲取年月日 int year = nowDate.getYear(); int monthValue = nowDate.getMonthValue(); int month = nowDate.getMonth().getValue(); int day = nowDate.getDayOfMonth(); int dayOfYear = nowDate.getDayOfYear(); int dayOfWeek = nowDate.getDayOfWeek().getValue(); System.out.println("year:" + year + ",monthValue:" + monthValue + ",month:" + month + ",day:" + day + ",dayOfYear:" + dayOfYear + ",dayOfWeek:" + dayOfWeek );
輸出:
year:2023,monthValue:5,month:5,day:11,dayOfYear:131,dayOfWeek:4
4、時(shí)間轉(zhuǎn)換
時(shí)間轉(zhuǎn)換,包括Date轉(zhuǎn)LocalDate、LocalTime、LocalDateTime;LocalDateTime轉(zhuǎn)Date,String轉(zhuǎn)LocalDate、LocalTime、LocalDateTime等。
parse(CharSequence text) :將字符串轉(zhuǎn)成對(duì)應(yīng)的LocalDate,LocalTime,LocalDateTime。
LocalDate of(int year, int month, int dayOfMonth) /LocalDate of(int year, Month month, int dayOfMonth) :設(shè)置年月日,轉(zhuǎn)成LocalDate。
如下面代碼:
//of() LocalDate ofDate = LocalDate.of(2022, Month.JANUARY, 31); System.out.println("of方法轉(zhuǎn)LocalDate;" + ofDate); //String轉(zhuǎn)LocalDate,LocalTime,LocalDateTime String date = "2020-01-01"; String time = "11:22:33"; String dateTime = "2021-09-06T09:51:51"; LocalDate localDate = LocalDate.parse(date); LocalTime localTime= LocalTime.parse(time); LocalDateTime localDateTime = LocalDateTime.parse(dateTime); System.out.println("String轉(zhuǎn)LocalDate,LocalTime,LocalDateTime,LocalDate;" + localDate + ",LocalTime:" + localTime + ",LocalDateTime:"+localDateTime); //date轉(zhuǎn)LocalDate,LocalTime,LocalDateTime Date date1 = new Date(); LocalDate localDate1 = LocalDateTime.ofInstant(date1.toInstant(), ZoneId.systemDefault()).toLocalDate(); LocalDateTime localDateTime1 = LocalDateTime.ofInstant(date1.toInstant(), ZoneId.systemDefault()); LocalTime localTime1 = LocalDateTime.ofInstant(date1.toInstant(), ZoneId.systemDefault()).toLocalTime(); System.out.println("date轉(zhuǎn)LocalDate,LocalTime,LocalDateTime,LocalDate;" + localDate1 + ",LocalTime:" + localTime1 + ",LocalDateTime:"+localDateTime1); //LocalDateTime轉(zhuǎn)Date Date from = Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); System.out.println("LocalDateTime轉(zhuǎn)Date;" + from );
輸出:
of方法轉(zhuǎn)LocalDate;2022-01-31
String轉(zhuǎn)LocalDate,LocalTime,LocalDateTime,LocalDate;2020-01-01,LocalTime:11:22:33,LocalDateTime:2021-09-06T09:51:51
date轉(zhuǎn)LocalDate,LocalTime,LocalDateTime,LocalDate;2023-05-11,LocalTime:14:30:02.562,LocalDateTime:2023-05-11T14:30:02.562
LocalDateTime轉(zhuǎn)Date;Thu May 11 14:30:02 CST 2023
5、日期比較
LocalDate中提供了equals,isAfter,isBefore等方法來對(duì)日期進(jìn)行比較,這對(duì)于我們業(yè)務(wù)代碼中時(shí)間判斷帶來了很大的方法。
equals(Object obj) :對(duì)比兩個(gè)日期是否相等,查看源碼會(huì)發(fā)現(xiàn),首先比較的是對(duì)象是否一樣,然后分別做年,月,日的差是否等于0來進(jìn)行比較。true:表示相等,false:表示不相等
compareTo(ChronoLocalDate other) :比較日期,0:表示相等,正數(shù):表示大于,負(fù)數(shù):表示小于。
isAfter(ChronoLocalDate other) :日期是否在other之后,true:表示是,false:表示否。相當(dāng)于compareTo正負(fù)數(shù)。
isBefore(ChronoLocalDate other) :日期是否在other之前,true:表示是,false:表示否。相當(dāng)于compareTo正負(fù)數(shù)。
//時(shí)間比較 LocalDate firDate = LocalDate.of(2022, 11, 23); LocalDate secDate = LocalDate.of(2023, 11, 23); LocalDate thrDate = LocalDate.of(2021, 11, 23); //equals System.out.println("equals:" + firDate.equals(secDate)); //compareTo System.out.println("compareTo1:" + secDate.compareTo(thrDate)); System.out.println("compareTo2:" + thrDate.compareTo(firDate)); //isAfter System.out.println("isAfter:" + firDate.isAfter(secDate)); System.out.println("isAfter:" + secDate.isAfter(thrDate)); //isBefore System.out.println("isBefore:" + firDate.isBefore(secDate)); System.out.println("isBefore:" + secDate.isBefore(thrDate));
輸出:
equals:false
compareTo1:2
compareTo2:-1
isAfter:false
isAfter:true
isBefore:true
isBefore:false
6、檢查周期性日期
在日常生活中,有許多紀(jì)念意義的日期,比如說生日,國慶等等。這時(shí)候需要進(jìn)行周期性檢查來做一些提醒,比如:老婆的生日,這要是忘了估計(jì)跪榴蓮都是輕的。哈哈哈
MonthDay這個(gè)類,就提供了of,from來獲取月份與當(dāng)前月份中第幾天,然后使用equals進(jìn)行比較即可。
//周期性檢查 LocalDate birthDay = LocalDate.of(1991, 5, 11); MonthDay birthMonth = MonthDay.of(birthDay.getMonth(), birthDay.getDayOfMonth()); MonthDay nowMonth = MonthDay.from(nowDate); if (Objects.equals(birthMonth,nowMonth)){ System.out.println("生日到了!"); } else { System.out.println("萬幸,還好生日還沒到呢,差點(diǎn)忘了......!"); }
輸出:
生日到了!
7、日期計(jì)算
前段時(shí)間做了一個(gè)需求,需要獲取前13個(gè)月的日期,這是使用LocalDate就比較方便,來看看LocalDate提供的方法。
提前:
minus(long amountToSubtract, TemporalUnit unit) :計(jì)算提前的日期,ChronoUnit實(shí)現(xiàn)了TemporalUnit接口,提供了各種日期類型,例如:
ChronoUnit.MONTHS,表示日期。
minusMonths(long monthsToSubtract) :計(jì)算提前月份的日期。
minusDays(long daysToSubtract) :計(jì)算提前天數(shù)的日期。
minusWeeks(long weeksToSubtract) :計(jì)算提前星期的日期。
minusYears(long yearsToSubtract) :計(jì)算提前年份的日期。
推后:
plus(long amountToSubtract, TemporalUnit unit) :計(jì)算推后的日期,ChronoUnit實(shí)現(xiàn)了TemporalUnit接口,提供了各種日期類型,例如:
ChronoUnit.MONTHS,表示日期。
plusMonths(long monthsToSubtract) :計(jì)算推后月份的日期。
plusDays(long daysToSubtract) :計(jì)算推后天數(shù)的日期。
plusWeeks(long weeksToSubtract) :計(jì)算推后星期的日期。
plusYears(long yearsToSubtract) :計(jì)算推后年份的日期。
LocalDate nowDate = LocalDate.now(); //日期計(jì)算 //提前 System.out.println("兩個(gè)月前的日期:" + nowDate.minusMonths(2)); System.out.println("20天前的日期:" + nowDate.minusDays(20)); System.out.println("1星期前的日期:" + nowDate.minusWeeks(1)); System.out.println("1年前的日期:" + nowDate.minusYears(1)); System.out.println("1個(gè)月前的日期:" + nowDate.minus(1, ChronoUnit.MONTHS)); //推后 System.out.println("兩個(gè)月后的日期:" + nowDate.plusMonths(2)); System.out.println("20天后的日期:" + nowDate.plusDays(20)); System.out.println("1星期后的日期:" + nowDate.plusWeeks(1)); System.out.println("1年后的日期:" + nowDate.plusYears(1)); System.out.println("1個(gè)月后的日期:" + nowDate.plus(1,ChronoUnit.MONTHS));
輸出:
兩個(gè)月前的日期:2023-03-11
20天前的日期:2023-04-21
1星期前的日期:2023-05-04
1年前的日期:2022-05-11
1個(gè)月前的日期:2023-04-11
兩個(gè)月后的日期:2023-07-11
20天后的日期:2023-05-31
1星期后的日期:2023-05-18
1年后的日期:2024-05-11
1個(gè)月后的日期:2023-06-11
8、處理時(shí)區(qū)
java8將時(shí)區(qū)也分離了出來,用ZoneId來處理特定時(shí)區(qū)。
ZoneDateTime:表示某時(shí)區(qū)下的時(shí)間。
//時(shí)區(qū) ZonedDateTime of = ZonedDateTime.of(nowDateTime, ZoneId.of("Asia/Shanghai")); System.out.println("時(shí)區(qū):" + of);
輸出:
時(shí)區(qū):2023-05-11T16:17:11.479+08:00[Asia/Shanghai]
9、獲取時(shí)間戳
java8提供了Instant類來對(duì)時(shí)間戳進(jìn)行操作。
System.out.println("時(shí)間戳:" + Instant.now().getEpochSecond());
時(shí)間戳返回的是秒級(jí)別的數(shù)據(jù)。
輸出:
時(shí)間戳:1683794339
10、閏年判斷
isLeapYear() :可以直接查詢?nèi)掌谑欠駷殚c年。true:表示是,false:表示否。
boolean leapYear = nowDate.isLeapYear(); if (leapYear){ System.out.println("閏年!"); } else { System.out.println("不是閏年!"); }
輸出:
不是閏年!
11、獲取第一天和最后一天
有時(shí)候我們業(yè)務(wù)需要獲取當(dāng)月或當(dāng)年的第一天日期或最后一天日期,TemporalAdjusters類提供了一些方法可以直接實(shí)現(xiàn)。
- TemporalAdjusters.lastDayOfMonth() :月份的最后一天日期。
- TemporalAdjusters.firstDayOfMonth() :月份的第一天日期。
- TemporalAdjusters.lastDayOfYear() :年份的最后一天日期。
- TemporalAdjusters.firstDayOfYear() :年份的第一天日期。
例如:獲取當(dāng)月/當(dāng)年的第一天日期和最后一天日期。
//獲取當(dāng)月第一天和最后一天 LocalDate lastDay = nowDate.with(TemporalAdjusters.lastDayOfMonth()); LocalDate firstDay = nowDate.with(TemporalAdjusters.firstDayOfMonth()); System.out.println("當(dāng)月第一天:"+firstDay + ";當(dāng)月最后一天:" + lastDay); //獲取當(dāng)年第一天和最后一天 LocalDate lastYearDay = nowDate.with(TemporalAdjusters.lastDayOfYear()); LocalDate firstYearDay = nowDate.with(TemporalAdjusters.firstDayOfYear()); System.out.println("當(dāng)年第一天:"+firstYearDay + ";當(dāng)月最后一天:" + lastYearDay);
輸出:
當(dāng)月第一天:2023-05-01;當(dāng)月最后一天:2023-05-31
當(dāng)年第一天:2023-01-01;當(dāng)月最后一天:2023-12-31
上述就是我在工作用到的一些java8日期時(shí)間的方法,存在完
以上就是Java8不可或缺小幫手之日期應(yīng)用的詳細(xì)內(nèi)容,更多關(guān)于Java8日期的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
關(guān)于SpringBoot禁止循環(huán)依賴解說
這篇文章主要介紹了關(guān)于SpringBoot禁止循環(huán)依賴解說,Spring的Bean管理,文章圍繞主題展開詳細(xì)介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-05-05MyBatis批量查詢、插入、更新、刪除的實(shí)現(xiàn)示例
由于需要處理短時(shí)間內(nèi)大量數(shù)據(jù)入庫的問題,想到了Mybatis的批量操作,本文主要介紹了MyBatis批量查詢、插入、更新、刪除的實(shí)現(xiàn)示例,感興趣的可以了解一下2023-05-05Java實(shí)現(xiàn)一個(gè)順序表的完整代碼
順序表是用一段物理地址連續(xù)的存儲(chǔ)單元依次存儲(chǔ)數(shù)據(jù)元素的線性結(jié)構(gòu),一般采用數(shù)組存儲(chǔ)。在數(shù)組上完成數(shù)據(jù)的增刪減改。順序表的底層是一個(gè)數(shù)組2021-04-04詳解Java中實(shí)現(xiàn)SHA1與MD5加密算法的基本方法
這篇文章主要介紹了詳解Java中實(shí)現(xiàn)SHA1與MD5加密算法的基本方法,安全哈希算法第一版和消息摘要算法第五版也是通常人們最常用的加密算法,需要的朋友可以參考下2016-04-04spring boot配置MySQL數(shù)據(jù)庫連接、Hikari連接池和Mybatis的簡單配置方法
這篇文章主要介紹了spring boot配置MySQL數(shù)據(jù)庫連接、Hikari連接池和Mybatis的簡單配置方法,需要的朋友可以參考下2018-03-03springboot2.3 整合mybatis-plus 高級(jí)功能(圖文詳解)
這篇文章主要介紹了springboot2.3 整合mybatis-plus 高級(jí)功能,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08如何開發(fā)基于Netty的HTTP/HTTPS應(yīng)用程序
HTTP/HTTPS是最常見的協(xié)議套件之一,并且隨著智能手機(jī)的成功,它的應(yīng)用也日益廣泛,因?yàn)閷?duì)于任何公司來說,擁有一個(gè)可以被移動(dòng)設(shè)備訪問的網(wǎng)站幾乎是必須的。下面就來看看如何開發(fā)基于Netty的HTTP/HTTPS應(yīng)用程序2021-06-06Spring?中?PageHelper?不生效問題及解決方法
這篇文章主要介紹了Spring?中?PageHelper?不生效問題,使用這個(gè)插件時(shí)要注意版本的問題,不同的版本可能 PageHelper 不會(huì)生效,本文結(jié)合示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-12-12