【问题标题】:how to convert mm/dd/yyyy to yyyy-mm-dd in java [duplicate]如何在java中将mm/dd/yyyy转换为yyyy-mm-dd [重复]
【发布时间】:2014-03-01 06:54:29
【问题描述】:

我将输入日期作为字符串输入 mm/dd/yyyy 并希望将其转换为 yyyy-mm-dd 我试试这段代码

Date Dob = new SimpleDateFormat("yyyy-mm-dd").parse(request.getParameter("dtDOB"));

【问题讨论】:

  • 好的,所以你解析了它......现在格式化它。

标签: java date format


【解决方案1】:

好的 - 你已经陷入了 java 日期格式最常见的陷阱之一:

  • mm分钟
  • MM

您已将月份解析为分钟。相反,将模式更改为:

Date dob = new SimpleDateFormat("yyyy-MM-dd").parse(...);

然后输出,再次确保您使用MM 几个月。

String str = new SimpleDateFormat("dd-MM-yyyy").format(dob);

【讨论】:

  • 嘿@Bohemian,恭喜获得钻石 :)
  • thanx 但此代码不起作用.. 给出以下错误 Unparseable date: "03/19/2014" at java.text.DateFormat.parse(Unknown Source)
  • @AnkitJain 从错误消息中可以看出原因:您的输入在日期部分之间有斜杠而不是破折号。尝试使用模式"dd/MM/yyyy"
  • @RohitJain 嘿,谢谢!我希望明年能在你的名字旁边看到一颗钻石。你是一个伟大的贡献者。我记得当你开始时,你发布了高质量的答案,当时我心想你会在这里走得很远。我是对的。
【解决方案2】:

应该是

SimpleDateFormat("yyyy-MM-dd")

资本M

更多信息请参考Oracle Docs

【讨论】:

    【解决方案3】:

    作为解析的替代方法,您可以使用正则表达式

    s = s.replaceAll("(\\d+)/(\\d+)/(\\d+)", "$3-$2-$1");
    

    【讨论】:

    • 创建日期时间对象的巧妙替代方案。
    【解决方案4】:

    前-

    String dob = "05/02/1989";  //its in MM/dd/yyyy
    String newDate = null;
    Date dtDob = new Date(dob);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    
    try {
          newDate = sdf.format(dtDob);
    } catch (ParseException e) {}
    
    System.out.println(newDate); //Output is 1989-05-02
    

    【讨论】:

      【解决方案5】:
      import java.text.ParseException;
      import java.text.SimpleDateFormat;
      import java.util.Date;
      
      public class FormatDate {
      
        private SimpleDateFormat inSDF = new SimpleDateFormat("mm/dd/yyyy");
        private SimpleDateFormat outSDF = new SimpleDateFormat("yyyy-mm-dd");
      
        public String formatDate(String inDate) {
          String outDate = "";
          if (inDate != null) {
              try {
                  Date date = inSDF.parse(inDate);
                  outDate = outSDF.format(date);
              } catch (ParseException ex) 
                  System.out.println("Unable to format date: " + inDate + e.getMessage());
                  e.printStackTrace();
              }
          }
          return outDate;
        }
      
        public static void main(String[] args) {
          FormatDate fd = new FormatDate();
          System.out.println(fd.formatDate("12/10/2013"));
        }
      
      }
      

      【讨论】:

      • 感谢您的解决方案...
      猜你喜欢
      • 1970-01-01
      • 2016-06-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      • 2011-03-18
      相关资源
      最近更新 更多