Java simpledateformat 格式化时将日期减少一天

在做项目中遇到一个很奇怪的问题,将日期进行格式化的时候居然将日期减少了一天,例如,日期为04 10,2023,格式化后日期为2023-04-09,代码如下:

String tableDate = "04 10,2023";
String dateTimeFormat = "MM dd,yyyy"
 
Date tableDateTime = DateUtils.parseDate(tableDate, dateTimeFormat);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String tableDateTimes = format.format(tableDateTime);
 
 
  /**
     * 验证是否是满足格式
     *
     * @param inputDate 要解析的字符串
     * @param format    格式
     * @return 解析出来的日期,如果没有匹配的返回null
     */
    public static Date parseDate(String inputDate, String format) {
        if (format == null || StringUtils.isEmpty(format.trim())) {
            return null;
        }
        try {
            // 默认的市区
            SimpleDateFormat df = new SimpleDateFormat(format, Locale.ENGLISH);
            // 解析英文格式
            SimpleDateFormat dfEn = new SimpleDateFormat(format, Locale.ENGLISH);
            // 解析中文日期格式
            SimpleDateFormat dfZH = new SimpleDateFormat(format, Locale.CHINESE);
            ParsePosition pos = new ParsePosition(0);
            // 默认
            // 设置解析日期格式是否严格解析日期
//            df.setLenient(false);
            df.setLenient(true);
            Date date = df.parse(inputDate, pos);
            // 英文
            dfEn.setLenient(false);
            Date dateEn = dfEn.parse(inputDate, pos);
            // 中文
            dfZH.setLenient(false);
            Date dateZh = dfZH.parse(inputDate, pos);
            if (date != null) {
                return date;
            } else if (dateEn != null) {
                return dateEn;
            } else if (dateZh != null) {
                return dateZh;
            }
        } catch (Exception e) {
            LOGGER.error("解析日期错误..");
            System.out.println("解析日期错误。。");
            return null;
        }
        return null;
    }

导致日期时间减少一天的原因是:可能由于时区导致日期转换不对。解决办法如下(时区可根据不同地方获取不同时区):

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
TimeZone zone = TimeZone.getTimeZone("MST");
format .setTimeZone(zone);
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值