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

Java实现dd/MM/yyyy与MM DD, yyyy日期格式双向转换求助

别着急,我来帮你搞定这个日期双向转换的问题!既然你没接触过日期格式化类,我会一步步给你讲清楚怎么实现,代码也会写得很直白。

日期双向转换实现方案

我们用Java 8及以上版本推荐的java.time包下的日期类(LocalDate)和格式化类(DateTimeFormatter)来实现,这比旧的Date/SimpleDateFormat更安全、易用。

1. 从 "dd/MM/yyyy" 转换到 "MM DD, yyyy"

比如把 10/10/1996 转成 Oct 10, 1996,步骤如下:

  • 定义输入格式的DateTimeFormatter:对应dd/MM/yyyy
  • 用这个格式把字符串解析成LocalDate对象
  • 定义输出格式的DateTimeFormatter:对应MMM dd, yyyy(MMM是月份的英文缩写,比如Oct)
  • 用输出格式把LocalDate格式化成目标字符串

代码示例:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class DateConverter {
    public static String convertToMonthDayYear(String ddMmYyyyDate) {
        // 输入格式:dd/MM/yyyy
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        // 输出格式:MMM dd, yyyy(自动生成英文月份缩写)
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("MMM dd, yyyy");
        
        try {
            LocalDate date = LocalDate.parse(ddMmYyyyDate, inputFormatter);
            return date.format(outputFormatter);
        } catch (DateTimeParseException e) {
            // 处理非法日期字符串的情况,比如输入"32/10/1996"这种无效日期
            System.out.println("输入的日期格式不正确,请检查!");
            return null;
        }
    }
}

测试调用:

public static void main(String[] args) {
    String originalDate = "10/10/1996";
    String convertedDate = convertToMonthDayYear(originalDate);
    System.out.println(convertedDate); // 输出:Oct 10, 1996
}

2. 从 "MM DD, yyyy" 转换到 "dd/MM/yyyy"

反过来把 Oct 10, 1996 转成 10/10/1996,步骤类似,只是交换输入和输出的格式:

代码示例(可以直接加到上面的DateConverter类里):

public static String convertToDdMmYyyy(String monthDayYearDate) {
    // 输入格式:MMM dd, yyyy
    DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("MMM dd, yyyy");
    // 输出格式:dd/MM/yyyy
    DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    
    try {
        LocalDate date = LocalDate.parse(monthDayYearDate, inputFormatter);
        return date.format(outputFormatter);
    } catch (DateTimeParseException e) {
        System.out.println("输入的日期格式不正确,请检查!");
        return null;
    }
}

测试调用:

public static void main(String[] args) {
    String originalDate = "Oct 10, 1996";
    String convertedDate = convertToDdMmYyyy(originalDate);
    System.out.println(convertedDate); // 输出:10/10/1996
}

注意事项

  • 确保你的Java版本是8或以上,java.time包是Java 8才引入的
  • 月份缩写(比如Oct)是英文的,如果需要其他语言的月份,可以给DateTimeFormatter指定Locale,比如DateTimeFormatter.ofPattern("MMM dd, yyyy", Locale.CHINESE)会生成中文月份
  • 一定要捕获DateTimeParseException,避免用户输入无效日期导致程序崩溃

你可以直接把这段代码复制到你的项目里测试,替换成你需要的日期字符串就行。如果有什么地方看不懂,随时问我!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:44:07