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 不存在的日期时,处理就容易出现问题,此处仅提供思路可以按照自己显示。
Calendar calendar = Calendar.getInstance(); calendar.setTime(date); // 设置为当前时间
如果出现不存在的日期会自动按照日期数进行推算
如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))){//如果当前日期不存在,系统会自动往后推。需要重置为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;
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
在2023idea中实现SpringBoot的IoC和AOP的方法
这篇文档详细介绍了如何在Spring Boot中实现IoC(控制反转)和AOP(面向切面编程),深入探讨了AOP的基本概念,包括AOP的作用、优势以及实现方式,最后,它提到了AOP的注解,如@Aspect、@Pointcut、@Before、@After、@AfterReturning、@AfterThrowing和@Around2024-11-11
关于Object中equals方法和hashCode方法判断的分析
今天小编就为大家分享一篇关于关于Object中equals方法和hashCode方法判断的分析,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧2019-01-01
Java并发J.U.C并发容器类list set queue
这篇文章主要为大家介绍了Java并发,J.U.C并发容器类list set queue,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-06-06


最新评论