Java8 LocalDateTime極簡時間日期操作小結(jié)
簡述
時間日期處理是平時工作中使用非常頻繁的邏輯,Java8中提供的新的時間類LocalDateTime和LocalDate,使日期處理可以更簡單。
友情提醒下,業(yè)務(wù)開發(fā)中最好默認使用LocalDateTime,因為LocalDateTime可以很方便的轉(zhuǎn)換為LocalDate,但是LocalDate是不可以轉(zhuǎn)為LocalDateTime的,會沒有時分秒的數(shù)據(jù)?。。?/p>
本篇文章整理了常用的日期處理獲取方式,并做簡要說明。
能寫一行的,就不寫兩行!文章會持續(xù)更新。
實例
1.獲取當前年月日的字符串
String ymd = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
DateTimeFormatter.ofPattern("yyyy-MM-dd"),修改獲取的日期格式
2.在當前日期上加減N天,N月,N年
獲取去年的日期,就是年份減1
LocalDate date = LocalDateTime.now().minusYears(1).toLocalDate();
獲取一年后的日期,就是年份加1
LocalDate date = LocalDateTime.now().plusYears(1).toLocalDate();
加的函數(shù)都是plus前綴的
同理,還有minus天,周,月的函數(shù),很方便
3.獲取上周的某天
獲取上周周一
LocalDate monday = LocalDate.now().minusWeeks(1).with(DayOfWeek.MONDAY);
DayOfWeek是java.time中的星期的枚舉,可通過枚舉值獲取一周中的任一天
返回的仍是LocalDate對象,方便進一步處理
4.當前時間是星期幾,這個月幾號,今年的第幾天
LocalDateTime dateTime = LocalDateTime.now(); System.out.println(dateTime.getDayOfWeek()); System.out.println(dateTime.getDayOfMonth()); System.out.println(dateTime.getDayOfYear());
5.獲取兩個日期中間的所有年份
public static List<Integer> getYearsBetweenTwoVar(LocalDate s, LocalDate e) {
LocalDate tmp = s.plusYears(1);
List<Integer> yearList = new ArrayList<>();
while (tmp.isBefore(e)) {
yearList.add(tmp.getYear());
tmp = tmp.plusYears(1);
}
return yearList;
}
補充:java8 LocalDateTime 格式化
LocalDateTime格式化
LocalDateTime time=LocalDateTime.now();
System.out.println(time);
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String strDate2 = dtf2.format(time);
System.out.println(strDate2);
LocalDate轉(zhuǎn)String ,String轉(zhuǎn)LocalDate
LocalDate data=LocalDate.now();
System.out.print(data);
DateTimeFormatter dtf3 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String strDate3 = dtf3.format(data);
System.out.println(strDate3);
strDate3=strDate3+" 04:00:00";
LocalDateTime time1=LocalDateTime.parse(strDate3,dtf2);
System.out.print(time1);
System.out.print(time.isAfter(time1));
總結(jié)
到此這篇關(guān)于Java8 LocalDateTime極簡時間日期操作整理的文章就介紹到這了,更多相關(guān)Java8 LocalDateTime 時間日期內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot設(shè)置接口超時的方法小結(jié)
這篇文章主要介紹了SpringBoot設(shè)置接口超時的方法小結(jié),包括配置文件,config配置類及相關(guān)示例代碼,代碼簡單易懂,對大家的學(xué)習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-09-09
java ArrayBlockingQueue的方法及缺點分析
在本篇內(nèi)容里小編給大家整理的是一篇關(guān)于java ArrayBlockingQueue的方法及缺點分析,對此有興趣的朋友們可以跟著學(xué)習下。2021-01-01
詳解在springboot中使用Mybatis Generator的兩種方式
這篇文章主要介紹了詳解在springboot中使用Mybatis Generator的兩種方式,本文將介紹到在springboot的項目中如何去配置和使用MBG以及MBG生成代碼的兩種方式,非常具有實用價值,需要的朋友可以參考下2018-11-11
解決JAVA遍歷List集合,刪除數(shù)據(jù)時出現(xiàn)的問題
這篇文章主要介紹了解決JAVA遍歷List集合時,刪除數(shù)據(jù)出現(xiàn)的問題,文中講解非常細致,幫助大家更好的理解和學(xué)習,感興趣的朋友可以了解下2020-07-07

