JAVA Calendar設(shè)置上個月時,日期不存在或錯誤提示問題及解決
更新時間:2025年12月11日 14:17:08 作者:辛晨V
在使用Java的Calendar類設(shè)置上個月的日期時,如果遇到不存在的日期(如4月31日),默認會自動調(diào)整到下個月的相應(yīng)日期(如5月1日),這是為了確保日期計算的準確性
JAVA Calendar設(shè)置上個月時,日期不存在或錯誤提示
java進行日期計算時
上個月日期一般使用:
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 設(shè)置為上一個月
進行,操作,但是當月份不存在、日期不存在如:4.31 2.31 不存在的日期時,處理就容易出現(xiàn)問題,此處僅提供思路可以按照自己顯示。
Calendar calendar = Calendar.getInstance(); calendar.setTime(date); // 設(shè)置為當前時間
如果出現(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); // 設(shè)置為當前時間
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); // 設(shè)置為上一個月
int newMonth = calendar.get(Calendar.MONTH);
if(oldMonth == newMonth){
calendar.set(Calendar.DATE, 1);
}
if(!time.equals(simpleDateFormat.format(date))){//判斷如果是當前日期不存在,需要往前推一天(如11.31應(yīng)該返回10.31)
calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 1); // 設(shè)置為上一個天
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;
}
}總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
在2023idea中實現(xiàn)SpringBoot的IoC和AOP的方法
這篇文檔詳細介紹了如何在Spring Boot中實現(xiàn)IoC(控制反轉(zhuǎn))和AOP(面向切面編程),深入探討了AOP的基本概念,包括AOP的作用、優(yōu)勢以及實現(xiàn)方式,最后,它提到了AOP的注解,如@Aspect、@Pointcut、@Before、@After、@AfterReturning、@AfterThrowing和@Around2024-11-11
關(guān)于Object中equals方法和hashCode方法判斷的分析
今天小編就為大家分享一篇關(guān)于關(guān)于Object中equals方法和hashCode方法判斷的分析,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-01-01
Java并發(fā)J.U.C并發(fā)容器類list set queue
這篇文章主要為大家介紹了Java并發(fā),J.U.C并發(fā)容器類list set queue,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-06-06
Jenkins+maven持續(xù)集成的實現(xiàn)
這篇文章主要介紹了Jenkins+maven持續(xù)集成的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04

