當前位置: 妍妍網 > 碼農

今日程式碼 PK | 日期時間處理

2024-03-17碼農

在我們平時的開發工作中,肯定離不開對日期時間的處理。

比如我現在需要獲取三天前的 0 點,大家都是怎麽做的呢?

是這樣嗎:

import java.util.Date;
public classMain {
publicstaticvoidmain(String[] args) {
// 獲取當前時間
DatecurrentDate = newDate();
// 計算三天前的時間
finallongDAY = 24 * 60 * 60 * 1000;
longthreeDaysAgoMillis = currentDate.getTime() - (3 * DAY);
DatethreeDaysAgoDate = newDate(threeDaysAgoMillis);
// 設定時間為0點
threeDaysAgoDate.setHours(0);
threeDaysAgoDate.setMinutes(0);
threeDaysAgoDate.setSeconds(0);
// 輸出結果
System.out.println("三天前的 0 點時間:" + threeDaysAgoDate);
}
}


其實 LocalDate 裏有很方便且現成的實作:

import java.time.LocalDate;
public classMain {
publicstaticvoidmain(String[] args) {
// 獲取當前日期
LocalDatetoday = LocalDate.now();
// 減去三天
LocalDatethreeDaysAgo = today.minusDays(3);
// 輸出三天前的0點時間
System.out.println("三天前的 0 點時間:" + threeDaysAgo.atStartOfDay());
}
}

大家更喜歡哪種呢?歡迎投票並在評論區留下自己的看法。

完整程式碼片段來源於程式碼小抄,歡迎點選進入小程式閱讀!

線上存取:https://www.codecopy.cn/post/k2j9rv

更多優質程式碼歡迎進入小程式檢視!

往期推薦