You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中将m/dd/yy格式字符串日期转换为yyyy/MM/dd的方法咨询

问题根因
  • 解析格式不匹配:你使用输出格式yyyy/MM/dd作为解析模板去解析输入格式M/dd/yy的字符串,本身就会解析失败或得到错误的日期对象
  • Date类toString()格式不符合预期:Date的toString()输出固定为EEE MMM dd HH:mm:ss zzz yyyy格式,不存在斜杠分隔符,用split("/")根本无法拆分得到正确的年月日
正确实现方案

Java 8及以上版本优先使用java.time包下的日期类实现,无需依赖老旧的SimpleDateFormat,没有线程安全问题,实现逻辑更简洁:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class DateConvertDemo {
    public static void main(String[] args) {
        String receiveDate = "7/20/21";
        int dueoffset = 1; // 替换为你自己的业务变量

        // 1. 定义输入日期的解析模板
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("M/dd/yy", Locale.US);
        // 2. 解析字符串为LocalDate对象
        LocalDate originalDate = LocalDate.parse(receiveDate, inputFormatter);
        // 3. 执行加天数的业务逻辑
        LocalDate calculatedDate = originalDate.plusDays(2 * dueoffset);
        // 4. 定义输出模板,格式化为目标格式字符串
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String targetDate = calculatedDate.format(outputFormatter);

        // 输出示例:如果dueoffset为1,会输出2021/07/22
        System.out.println(targetDate);
    }
}
注意事项

两位年份的默认匹配规则为:取值在1950~2049区间,如果你的业务场景需要自定义年份映射规则,可以通过DateTimeFormatterBuilder构造器调整appendValueReduced参数实现。

内容的提问来源于stack exchange,提问作者JavaDeveloper2024

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 21:42:03