[英]convert string into date format in java
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)
Well yes. 嗯,是。 The argument you pass into the constructor of
SimpleDateFormat
says the format you expect the date to be in. 传递给
SimpleDateFormat
构造函数的参数说明了您期望日期所在的格式。
"EEEE, MMMM/dd/yyyy"
would be valid for input like "Tuesday, February/26/2013". "EEEE, MMMM/dd/yyyy"
对“2013年2月26日星期二”等输入有效。 It's not even slightly valid for "2-26-2013". 它甚至不是稍微有效期为“2013年2月26日”。 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 "Md-yyyy". 看起来你想要一个格式字符串“M-dd-yyyy”或者可能是“Md-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);
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. SimpleDateFormat的参数定义了它的日期格式。上面的行符合您的格式,并且有效。 Your example does not match.
你的例子不匹配。
Instead of using MMMM/dd/yyyy
you need to used MM-dd-yyyy
. 而不是使用
MMMM/dd/yyyy
你需要使用MM-dd-yyyy
。 SimpleDateFormat expects the pattern to match what its trying to parse. SimpleDateFormat期望该模式与其尝试解析的模式匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.