1.獲取當(dāng)前時(shí)間的整點(diǎn)時(shí)間點(diǎn)
如:2022-12-02 17:38:24
得到:2022-12-02 17:00:00
LocalDateTime localDateTime = LocalDateTime.now().toLocalDate().atTime(LocalDateTime.now().getHour(), 0, 0);
2.獲取當(dāng)前時(shí)間的下一個(gè)整點(diǎn)時(shí)間點(diǎn)
如:2022-12-02 17:38:24
得到:2022-12-02 18:00:00
LocalDateTime localDateTime = LocalDateTime.now().toLocalDate().atTime(LocalDateTime.now().plusHours(1).getHour(), 0, 0);
3.字符串轉(zhuǎn)換LocalDateTime
String st ="2022-12-02 17:38:24" ;
LocalDateTime parse = LocalDateTime.parse(st, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
4.LocalDate 轉(zhuǎn) LocalDateTime
一般調(diào)用 atTime() 方法進(jìn)行賦值
LocalDate localDate = LocalDate.now();
LocalDateTime localDateTime1 = localDate.atStartOfDay();
LocalDateTime localDateTime2 = localDate.atTime(8,20,33);
LocalDateTime localDateTime3 = localDate.atTime(LocalTime.now());
5.時(shí)間大小比較
now 和 ph 比較 ,
如果=0,表示時(shí)間相同,
小于0,表示now比ph?。╪ow在ph時(shí)間點(diǎn)之前,如2022-12-02 15:00:00 在 2022-12-02 15:30:00之前),
大于0,now比ph大(now在ph時(shí)間點(diǎn)之后,如2022-12-02 17:00:00 在 2022-12-02 15:30:00之后)
LocalDateTime ph = LocalDateTime.now().plusHours(1);
LocalDateTime now = LocalDateTime.now();
boolean a =Duration.between(now , ph).getSeconds()<=0
6.LocalDate 轉(zhuǎn) Date
先調(diào)用 atStartOfDay() 方法轉(zhuǎn) LocalDateTime 再轉(zhuǎn) Date
LocalDate localDate = LocalDate.now();
ZoneId zoneId = ZoneId.systemDefault();
Date date = Date.from(localDate.atStartOfDay().atZone(zoneId).toInstant());
7.Date轉(zhuǎn)LocalDate
Date date = new Date();
ZoneId zoneId = ZoneId.systemDefault();
LocalDate localDate = date.toInstant().atZone(zoneId).toLocalDate();
8.LocalDateTime轉(zhuǎn)Date
在LocalDateTime 轉(zhuǎn) Date 時(shí),需要使用到 Java 8的幾個(gè)類
ZoneId/ZoneOffset:表示時(shí)區(qū)
ZonedDateTime: 表示特定時(shí)區(qū)的日期和時(shí)間
Instant:表示時(shí)刻,不直接對(duì)應(yīng)年月日信息,需要通過時(shí)區(qū)轉(zhuǎn)換
//d當(dāng)前時(shí)間
LocalDateTime localDateTime = LocalDateTime.now();
//系統(tǒng)的默認(rèn)時(shí)區(qū)
ZoneId zoneId = ZoneId.systemDefault();
//時(shí)區(qū)的日期和時(shí)間
ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId);
//獲取時(shí)刻
Date date = Date.from(zonedDateTime.toInstant());
System.out.println("格式化前:localDateTime:" + localDateTime + " Date:" + date);
//格式化LocalDateTime、Date
DateTimeFormatter localDateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("格式化后:localDateTime:" + localDateTimeFormat.format(localDateTime) + " Date:" + dateFormat.format(date));
9.Date 轉(zhuǎn) LocalDateTime
Date date = new Date();
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime = date.toInstant().atZone(zoneId).toLocalDateTime();
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機(jī)房具備T級(jí)流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級(jí)服務(wù)器適合批量采購,新人活動(dòng)首月15元起,快前往官網(wǎng)查看詳情吧