如何在java中将mm/dd/yyyy转换为yyyy-mm-dd

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22111209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:39:53  来源:igfitidea点击:

how to convert mm/dd/yyyy to yyyy-mm-dd in java

javadateformat

提问by Ankit Jain

i am getting input date as String into mm/dd/yyyy and want to convert it into yyyy-mm-dd i try out this code

我正在将输入日期作为字符串输入 mm/dd/yyyy 并想将其转换为 yyyy-mm-dd 我试试这个代码

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

回答by Bohemian

OK - you've fallen for one of the most common traps with java date formats:

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

  • mmis minutes
  • MMis months
  • mm分钟
  • MM几个月

You have parsed months as minutes. Instead, change the pattern to:

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

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

Then to output, again make sure you use MMfor months.

然后要输出,再次确保你用MM了几个月。

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

回答by Kamlesh Arya

It should be

它应该是

SimpleDateFormat("yyyy-MM-dd")

capital M

大写M

For More info refer Oracle Docs

有关更多信息,请参阅 Oracle 文档

回答by Evgeniy Dorofeev

As alternative to parsing you can use regex

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

s = s.replaceAll("(\d+)/(\d+)/(\d+)", "--");

回答by Rahul

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"));
  }

}

回答by Arjit

Ex -

前任 -

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