当我使用 setLenient() 时,SimpleDateFormat 不解析带有日期的字符串

SimpleDateFormat don't parse a string with a date when I use setLenient()

我不明白下面的代码出了什么问题:

SimpleDateFormat formatter = new SimpleDateFormat("MM.dd.yy hh:mm:ss");
formatter.setLenient(false);
formatter.parse("04.29.2017 00:55:05");

当我尝试用日期解析字符串时,我得到了 java.text.ParseException。我的代码有什么问题?

hh 期望范围为 1 到 12。如果您希望它在 lenient off 下工作,请将其更改为 HH(0 到 23)。

您需要使用 yyyy 格式(因为 2017 年是 yyyy)。

我还删除了 formatter.setLenient(false);,因为这不是必需的。

像这样:

public class DateParse {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("MM.dd.yyyy hh:mm:ss");
        Date myDate = formatter.parse("04.29.2017 00:55:05");

        System.out.println(myDate);
    }
}

输出:

Sat Apr 29 00:55:05 BST 2017