在java中将字符串转换为日期格式 [英] 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);
我收到此错误:
Exception in thread "main" java.text.ParseException: Unparseable date: "2-26-2013"
at java.text.DateFormat.parse(DateFormat.java:357)
推荐答案
是的。传递给 SimpleDateFormat
的构造函数的参数表示您希望日期所在的格式。
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
对2013年2月26日星期二等输入有效。对于2-26-2013,它甚至略无效。你明白你现在正在解析文本,而不是格式化它吗?
"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?
看起来你想要一个格式字符串 M-dd-yyyy或者可能是Md-yyyy。
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);
这篇关于在java中将字符串转换为日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!