convert string into date format in java

南楼画角 提交于 2019-12-20 04:43:50

问题


I want to convert this string to the following date format.

  String s = "2-26-2013";
  Date date = new SimpleDateFormat("EEEE, MMMM/dd/yyyy").parse(s);
  System.out.println(date);

I'm getting this error:

Exception in thread "main" java.text.ParseException: Unparseable date: "2-26-2013"
    at java.text.DateFormat.parse(DateFormat.java:357)

回答1:


Well yes. The argument you pass into the constructor of SimpleDateFormat says the format you expect the date to be in.

"EEEE, MMMM/dd/yyyy" would be valid for input like "Tuesday, February/26/2013". It's not even slightly valid for "2-26-2013". You do understand that you're parsing the text at the moment, not formatting it?

It looks like you want a format string of "M-dd-yyyy" or possibly "M-d-yyyy".

If you're trying to convert from one format to another, you need to first specify the format to parse, and then specify the format to format with:

SimpleDateFormat parser = new SimpleDateFormat("M-dd-yyyy");
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMMM/dd/yyyy");
Date date = parser.parse(input);
String output = formatter.format(date);



回答2:


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

The argument to SimpleDateFormat defines the format your date it in. The above line matches your format, and works. Your example does not match.




回答3:


Instead of using MMMM/dd/yyyy you need to used MM-dd-yyyy. SimpleDateFormat expects the pattern to match what its trying to parse.



来源:https://stackoverflow.com/questions/15085771/convert-string-into-date-format-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!