java does not parse for 'M dd, yyyy' date

2019-03-05 09:29发布

I want to parse date strings like "February 7, 2011" using "M dd, yyyy" format. But I get an exception.

4条回答
兄弟一词,经得起流年.
2楼-- · 2019-03-05 09:48

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);
查看更多
Deceive 欺骗
3楼-- · 2019-03-05 09:50

You will want to use "MMM dd, yyyy"

SimpleDateFormat("MMM dd, yyyy").parse("February 7, 2011")

See SimpleDateFormat

查看更多
仙女界的扛把子
4楼-- · 2019-03-05 10:04

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);
    }
}
查看更多
疯言疯语
5楼-- · 2019-03-05 10:06
  • 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");
查看更多
登录 后发表回答