JAVA Calendar 设置上个月时,日期不存在或错误提示

java进行日期计算时,上个月日期一般使用:
 

 calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月

进行,操作,但是当月份不存在、日期不存在如:4.31 2.31 不存在的日期时,处理就容易出现问题,此处仅提供思路可以按照自己显示。

Calendar calendar = Calendar.getInstance();
calendar.setTime(date); // 设置为当前时间

1、如果出现不存在的日期会自动按照日期数进行推算,如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;
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值