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

Java中如何将mm/dd/yy格式字符串转为YYYY-MM-DD格式Date?

解决mm/dd/yy格式字符串转YYYY-MM-DD风格Date对象的问题

嗨,我来帮你搞定这个日期转换的问题!你遇到的ParseException其实原因很直接:你的解析格式和输入字符串的格式完全不匹配。

你输入的是03/01/18(mm/dd/yy格式:月/日/两位年份),但代码里用了yyyy-MM-dd(年-月-日)的格式去解析,系统自然识别不了,所以抛出了异常。

下面给你两种可行的解决方案,分别适配不同的Java版本:

方案一:使用传统的SimpleDateFormat(Java 8及以前)

核心思路是:先用和输入格式匹配的MM/dd/yy解析字符串得到Date对象,再根据需求格式化为YYYY-MM-DD的字符串(注意:Date对象本身是不带格式的,它本质是一个时间戳,格式只是显示层面的转换)。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateConverter {
    public static Date stringToDateLinen(String dateValue) {
        Date date = null;
        // 第一步:用输入对应的格式解析字符串
        SimpleDateFormat inputFormatter = new SimpleDateFormat("MM/dd/yy");
        try {
            date = inputFormatter.parse(dateValue);
            // 如果需要输出YYYY-MM-DD格式的字符串,可以再做一次格式化
            SimpleDateFormat outputFormatter = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = outputFormatter.format(date);
            System.out.println("格式化后的日期字符串:" + formattedDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static void main(String[] args) {
        stringToDateLinen("03/01/18"); // 输出格式化后的字符串为2018-03-01
    }
}

⚠️ 注意:SimpleDateFormat是线程不安全的,不要把它声明为静态变量在多线程环境下使用,最好每次使用时创建实例,或者用ThreadLocal来维护。

另外,关于两位年份yy的解析:默认情况下,Java会把18解析为2018,如果需要指定世纪范围(比如把18解析为1918),可以设置inputFormatter.set2DigitYearStart(new GregorianCalendar(1900, 0, 1).getTime());。

方案二:使用Java 8+的DateTimeFormatter(推荐)

Java 8引入的java.time包是线程安全且API更清晰的日期处理方案,推荐优先使用:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.time.ZoneId;

public class DateConverter {
    public static LocalDate stringToLocalDate(String dateValue) {
        // 解析输入格式为LocalDate
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("MM/dd/yy");
        LocalDate localDate = LocalDate.parse(dateValue, inputFormatter);
        
        // 转换为YYYY-MM-DD格式的字符串
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedDate = outputFormatter.format(localDate);
        System.out.println("格式化后的日期字符串:" + formattedDate);
        
        return localDate;
    }

    // 如果确实需要转换为旧的Date对象(适配旧API)
    public static Date localDateToDate(LocalDate localDate) {
        return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }

    public static void main(String[] args) {
        LocalDate localDate = stringToLocalDate("03/01/18");
        Date date = localDateToDate(localDate);
    }
}

这个方案里,LocalDate专门处理日期(不带时间),DateTimeFormatter是线程安全的,比SimpleDateFormat更可靠。

内容的提问来源于stack exchange,提问作者S Mugunthan kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:24:35