JAVA Calendar設置上個月時,日期不存在或錯誤提示問題及解決
更新時間:2025年12月11日 14:17:08 作者:辛晨V
在使用Java的Calendar類設置上個月的日期時,如果遇到不存在的日期(如4月31日),默認會自動調整到下個月的相應日期(如5月1日),這是為了確保日期計算的準確性
JAVA Calendar設置上個月時,日期不存在或錯誤提示
java進行日期計算時
上個月日期一般使用:
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 設置為上一個月
進行,操作,但是當月份不存在、日期不存在如:4.31 2.31 不存在的日期時,處理就容易出現(xiàn)問題,此處僅提供思路可以按照自己顯示。
Calendar calendar = Calendar.getInstance(); calendar.setTime(date); // 設置為當前時間
如果出現(xiàn)不存在的日期會自動按照日期數(shù)進行推算
如4.31會自動生成5.1 2.31會自動生成3.3號,并不是所有的都順延到下個月1號。
知道這里就知道該怎么辦了
/**
* 獲取上個月的今天
* @param time
* @return
*/
public static String getPreviousMonth(String time,String SimpleDateFormat) {
try {
if(StringUtils.isBlank(time)){
return "";
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(SimpleDateFormat);//注意月份是MM
Date date = simpleDateFormat.parse(time);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date); // 設置為當前時間
if(!time.equals(simpleDateFormat.format(date))){//如果當前日期不存在,系統(tǒng)會自動往后推。需要重置為1號
calendar.set(Calendar.DATE, 1); //
}
int oldMonth = calendar.get(Calendar.MONTH);
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 設置為上一個月
int newMonth = calendar.get(Calendar.MONTH);
if(oldMonth == newMonth){
calendar.set(Calendar.DATE, 1);
}
if(!time.equals(simpleDateFormat.format(date))){//判斷如果是當前日期不存在,需要往前推一天(如11.31應該返回10.31)
calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 1); // 設置為上一個天
calendar.getTime();
int day = Integer.parseInt(StringUtils.substring(time, StringUtils.lastIndexOf(time, "-") + 1, time.length()));
calendar.set(Calendar.DATE, day);
}
date = calendar.getTime();
return simpleDateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
SpringSecurity+Redis+Jwt實現(xiàn)用戶認證授權
SpringSecurity是一個強大且靈活的身份驗證和訪問控制框架,本文主要介紹了SpringSecurity+Redis+Jwt實現(xiàn)用戶認證授權,具有一定的參考價值,感興趣的可以了解一下2024-07-07

