java - SimpleDateFormat 没有按预期工作

标签 java date simpledateformat

<分区>

我尝试使用此功能,但它不适用于“12/05/201a”这种情况,有人知道为什么会这样吗?

在我的测试中,我使用了这个 System.out.println(isThisDateValid("12/05/201a", "dd/MM/yyyy")); 并且答案是 true 但我预计结果会是错误的,因为年份包含字母。

 public static boolean isThisDateValid(String dateToValidate, String dateFromat)
    {

        if (dateToValidate == null)
        {
            return false;
        }

        SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
        sdf.setLenient(false);

        try
        {

            //if not valid, it will throw ParseException
            Date date = sdf.parse(dateToValidate);
            System.out.println(date);

        } catch (ParseException e)
        {

            e.printStackTrace();
            return false;
        }

        return true;
    }

最佳答案

DateFormat#parse不一定使用整个字符串:

Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.

(我的重点)

SimpleDateFormat's docs告诉我们 yyyy 并不一定意味着一年需要四位数字:

Year:

...

  • For parsing, if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits. So using the pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12 A.D.

所以它在 201 年解析该字符串是正确的(如果可能令人惊讶的话)。

您可以使用 parse(String,ParsePosition)弄清楚整个字符串是否已被使用,或者在解析之前使用正则表达式对其进行验证。这是一个版本,它将检查整个字符串是否已被解析,而不仅仅是第一个字符:

public static boolean isThisDateValid(String dateToValidate, String dateFormat) {
    if (dateToValidate == null) {
        return false;
    }

    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
    sdf.setLenient(false);

    ParsePosition position = new ParsePosition(0);
    Date date = sdf.parse(dateToValidate, position);
    return date != null && position.getIndex() == dateToValidate.length();
}

关于java - SimpleDateFormat 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31657964/

相关文章:

java - 如何用java解析这个文本文件?

java - FXLauncher - 安装后是否可以更改/更新 JRE

java - 嵌套异常是 java.lang.NoClassDefFoundError : Could not initialize class com. my.util.HibernateUtil

php - Drupal 7 calendar_row_plugin 丢失,日历 block 错误

java - 考虑夏令时转换为 UTC

java - 在Java中显示Excel工作表xlsx中的日期

java - 为什么我的 simpleDateFormat 搞砸了星期几?

java - SimpleDateFormat 无法解析超过 4 位的毫秒数

java - 需要建议 : A programmatic way for creating vector graphics with heavy usage of text

java - 如何检测 Google 电子表格中的更改? java