Java獲取某一日期的前N天(使用Calendar類)
獲取當前日期的前一天,可以使用 Java 自帶的 Calendar 類,這里提供兩種實現(xiàn)方式:
使用 Calendar 類
// 獲取 Calendar 實例 Calendar calendar = Calendar.getInstance(); // 設置為當前日期 calendar.setTime(new Date()); // 將日期減去一天 calendar.add(Calendar.DATE, -1); // 獲取前一天日期 Date yesterday = calendar.getTime();
使用 Java 8 新特性 LocalDate
// 獲取當前日期 LocalDate today = LocalDate.now(); // 獲取前一天日期 LocalDate yesterday = today.minusDays(1); // 轉換為 Date 類型 Date date = Date.from(yesterday.atStartOfDay(ZoneId.systemDefault()).toInstant());
第二種方法使用了 Java 8 中引入的新日期時間 API,可以更方便地進行日期計算,不過需要注意,由于其是在 Java 8 中引入的,如果你的項目使用的是舊版本的 Java,則該方法不可用。
附:獲取n天后的對應的工作日日期
/**
*
* 根據(jù)開始日期 ,需要的工作日天數(shù) ,計算n天后的日期(周六日不包含)
* @param startDate 開始日期
* @param workDays 天數(shù)
*
*/
public static String getAfterWorkDays(Date startDate, int workDays) {
Calendar c1 = Calendar.getInstance();
c1.setTime(startDate);
for (int i = 0; i < workDays; i++) {
c1.set(Calendar.DATE, c1.get(Calendar.DATE) + 1);
if (Calendar.SATURDAY == c1.get(Calendar.SATURDAY) || Calendar.SUNDAY == c1.get(Calendar.SUNDAY)) {
workDays = workDays + 1;
c1.set(Calendar.DATE, c1.get(Calendar.DATE) + 1);
continue;
}
}
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(df.format(c1.getTime()) + " " + getWeekOfDate(c1.getTime()));
return df.format(c1.getTime());
}總結
到此這篇關于Java獲取某一日期的前N天的文章就介紹到這了,更多相關Java獲取日期前N天內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java通過Process類Runtime.getRuntime().exec()執(zhí)行bat腳本程序
用Java編寫應用時,有時需要在程序中調用另一個現(xiàn)成的可執(zhí)行程序或系統(tǒng)命令,這篇文章主要給大家介紹了關于Java如何通過Process類Runtime.getRuntime().exec()執(zhí)行bat腳本程序的相關資料,需要的朋友可以參考下2024-01-01
Spring數(shù)據(jù)庫多數(shù)據(jù)源路由配置過程圖解
這篇文章主要介紹了Spring數(shù)據(jù)庫多數(shù)據(jù)源路由配置過程圖解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-06-06
MyBatis注解開發(fā)-@Insert和@InsertProvider的使用
這篇文章主要介紹了MyBatis注解開發(fā)-@Insert和@InsertProvider的使用,具有很好的參考價值,希望對大家有所幫助。2022-07-07
Springboot整合camunda+mysql的集成流程分析
本文介紹基于mysql數(shù)據(jù)庫,如何實現(xiàn)camunda與springboot的集成,如何實現(xiàn)基于springboot運行camunda開源流程引擎,本文分步驟圖文相結合給大家介紹的非常詳細,需要的朋友參考下吧2021-06-06
Java網(wǎng)絡編程之UDP網(wǎng)絡通信詳解
這篇文章主要為大家詳細介紹了Java網(wǎng)絡編程中的UDP網(wǎng)絡通信的原理與實現(xiàn),文中的示例代碼講解詳細,具有一定的借鑒價值,需要的可以參考一下2022-09-09

