验证字符串“2 Sep 2018 09:00”是有效的日期格式

Verify the string " 2 Sep 2018 09:00 " is a valid date format

我知道有多个问题要求验证有效日期。但我无法找出确切的格式。所以请不要将其标记为重复。

我的网页中有一个以字符串形式返回的日期,例如 2 Sep 2018 09:00。作为我的硒测试的一部分,我需要验证这是一个日期。感谢有人可以帮助我验证这是 Java.

中的有效日期格式

谢谢

我找到了一个方法。发布,因为它会有用。

            String dateformat = "A valid date time format";
    String notValidDateFormat = "Not a valid date time format" ;
    final DateFormat fmt = new SimpleDateFormat("dd MMM yyyy hh:mm");
    Date input = null;
    try {
        input = fmt.parse(offerDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    if (input.before(new Date())) {
        return dateformat;
    }
    return notValidDateFormat;
}

需要您的用户区域设置的标准格式

    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(
                    FormatStyle.MEDIUM, FormatStyle.SHORT)
            .withLocale(Locale.UK);
    ZoneId userTimeZone = ZoneId.of("Europe/London");
    // Require a comma between date and time
    String returnedFromWebPage = "2 Sep 2018, 09:00";
    // Remove any space before the date or after the time
    returnedFromWebPage = returnedFromWebPage.trim();
    try {
        ZonedDateTime dateTime = LocalDateTime.parse(returnedFromWebPage, formatter)
                .atZone(userTimeZone);
        if (dateTime.isBefore(ZonedDateTime.now(userTimeZone))) {
            System.out.println("A valid date time");
        } else {
            System.out.println("Not in the past");
        }
    } catch (DateTimeParseException dtpe) {
        System.out.println("Not a valid date time format");
    }

运行 在 Java 10 时的输出:

A valid date time

Java 10 with default locale data 认为英国的日期和时间符号可能会像 2 Sep 2018, 09:00 (取决于你想要多长或多短),也就是说,日期和时间之间的逗号,否则就像您的输入字符串一样。因此,一个建议是查看您的用户是否同意并以这种方式输入日期和时间。如果这符合英国规范是正确的,我想他们会很乐意的。

现在我根本不知道你的用户是不是英国人。 Java 具有数百个语言环境的本地化格式。我认为您应该首先使用用户的语言环境。如果他们碰巧说斯瓦希里语,标准格式似乎没有逗号:

    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(
                    FormatStyle.MEDIUM, FormatStyle.SHORT)
            .withLocale(Locale.forLanguageTag("sw"));
    ZoneId userTimeZone = ZoneId.of("Africa/Nairobi");
    String returnedFromWebPage = "2 Sep 2018 09:00";

通过这些更改,代码还会打印 A valid date time

如果需要,构建您自己的格式化程序

如果您的用户对 Java 中的任何内置格式不满意,您将需要指定他们想要使用的格式:

    DateTimeFormatter formatter 
            = DateTimeFormatter.ofPattern("d MMM uuuu HH:mm", Locale.ENGLISH);
    String returnedFromWebPage = "2 Sep 2018 09:00";

这也会导致代码打印 A valid date time