使用先决条件以特定格式验证日期

validate date in a particular format using preconditions

我有一个字符串格式的日期 YYYY/MM/DD HH:MM:SS,我需要使用先决条件 google 番石榴 class 来验证它。我在很多其他地方使用 checkArgument 方法。我如何使用 checkArgument 方法来验证 startDate 以确保它仅采用这种格式 YYYY/MM/DD HH:MM:SS,如果不是,则抛出带有一些消息的 IllegalArgumentException。

public Builder startDate(String startDate) {
    // validate startDate here using checkArgument if it is not valid then throw IllegalArgumentException.
    this.sDate = startDate;
    return this;
}

如何在这里使用 checkArgument 方法?

您可以根据正则表达式测试整个字符串:

Preconditions.checkArguments(str.matches(VALID_DATE_REGEX));

为了加快速度,您可以编译模式一次并反转调用

Preconditions.checkArgument(VALID_DATE_REGEX.matcher(str).matches());

但是这是一种气味。你不应该在你的程序中来回携带这串文本:如果你需要那种格式,那只是因为在某个时候你会把它转换成一个日期。因此,您最好决定您的程序是否可以接受无效输入并将其报告给用户,或者是否应立即终止。

后者更容易处理:立即解析文本并抛出无效输入的异常。否则,您需要在程序中引入一个验证步骤,然后编写一种方法来停止流程并向用户显示输入中的任何阻塞和 non-blocking 错误。

不要。写入

 try {
   new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(startDate);
 } catch (ParseException e) {
   throw new IllegalArgumentException(e);
 }

..这也可以让你存储 Date 解析并在以后使用它。 (虽然,公平地说,java.util.Date 是一个可怕的 API 最好避免——但你暗示你在之前的问题中使用过它,你似乎已经删除了。)

如果您最终使用 Joda Time,http://joda-time.sourceforge.net/userguide.html#Input_and_Output 会解释如何根据这些需求调整此答案。

是正确的。他提到避免 java.util.Date.

java.time

java.util.Date class 及其搭档 java.util.Calendar 已在 Java 8 及更高版本中被 java.time framework. See the Oracle Tutorial 取代。

我们使用DateTimeFormatter and DateTimeParseException classes instead. Contained in the java.time.format包。

这是他使用 java.time classes 的答案的等价物。

try {
    DateTimeFormatter.ofPattern ( "yyyy/MM/dd HH:mm:ss" ).parse ( input );
} catch ( e ) {
    throw new DateTimeParseException ( e );
}

Joda-Time

对于无法迁移到 Java 8 或更高版本的用户,请将 Joda-Time 库添加到您的项目中。 Joda-Time 为 java.time 提供了灵感,两个框架共享相同的概念。

applies to our solution: Make a parse attempt, and catch an exception. We use the DateTimeFormatter class from Joda-Time which throws a standard Java IllegalArgumentException 遇到错误输入时。

try {
    DateTimeFormatter formatter = DateTimeFormat.forPattern ( "yyyy/MM/dd HH:mm:ss" );
    DateTime dt = formatter.parseDateTime ( input );
} catch ( e ) {
    throw new IllegalArgumentException ( e );
}