I want to parse date strings like "February 7, 2011"
using "M dd, yyyy"
format. But I get an exception.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
- Your parsing string is not correct as mentioned by others
- To correctly parse
February
you need to use an english Locale or it may fail if your default Locale is not in English
DateFormat df = new SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH);
Date dt = df.parse("February 7, 2011");
回答2:
Try this code. I ran it with two dates "November 20, 2012" and "January 4, 1957" and got this output:
arg: November 20, 2012 date: Tue Nov 20 00:00:00 EST 2012
arg: January 4, 1957 date: Fri Jan 04 00:00:00 EST 1957
It works fine. Your regex was wrong.
package cruft;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* DateValidator
* @author Michael
* @since 12/24/10
*/
public class DateValidator {
private static final DateFormat DEFAULT_FORMATTER;
static {
DEFAULT_FORMATTER = new SimpleDateFormat("MMM dd, yyyy");
DEFAULT_FORMATTER.setLenient(false);
}
public static void main(String[] args) {
for (String dateString : args) {
try {
System.out.println("arg: " + dateString + " date: " + convertDateString(dateString));
} catch (ParseException e) {
System.out.println("could not parse " + dateString);
}
}
}
public static Date convertDateString(String dateString) throws ParseException {
return DEFAULT_FORMATTER.parse(dateString);
}
}
回答3:
You will want to use "MMM dd, yyyy"
SimpleDateFormat("MMM dd, yyyy").parse("February 7, 2011")
See SimpleDateFormat
回答4:
Assuming you are using SimpleDateFormat
, the month format is incorrect, it should be MMM dd, yyyy
MMM
will match the long text format of the month:
String str = "February 7, 2011";
SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy");
Date date = format.parse(str);