gpt4 book ai didi

java - 验证字符串 "2 Sep 2018 09:00 "是有效的日期格式

转载 作者:行者123 更新时间:2023-12-02 01:55:07 25 4
gpt4 key购买 nike

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

我的网页中有一个以字符串形式返回的日期,例如 2018 年 9 月 2 日 09:00。我需要验证这是一个日期,作为我的 Selenium 测试的一部分。如果有人能帮助我验证它是否为 Java 中的有效日期格式,我将不胜感激。

谢谢

最佳答案

需要用户所在区域的标准格式

    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 认为英国的日期和时间表示法可能类似于 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";

通过这些更改,代码还会打印有效的日期时间

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

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

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

这也会导致代码打印有效的日期时间

关于java - 验证字符串 "2 Sep 2018 09:00 "是有效的日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52415487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com