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

醉酒当歌 提交于 2019-12-02 10:22:24
  • 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");

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);
    }
}

You will want to use "MMM dd, yyyy"

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

See SimpleDateFormat

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