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

2022-01-15 00:00:00 format date java

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

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

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

推荐答案

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

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

  • mm 为 分钟
  • MM 是 月
  • mm is minutes
  • MM is months

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

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

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

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

Then to output, again make sure you use MM for months.

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

相关文章