使用 java Date 和 SimpleDateFormat 验证范围

发布于 2024-10-06 19:31:41 字数 386 浏览 0 评论 0原文

当我尝试用这里的代码解析日期时,是否有一个日期异常可以处理:

try{
   SimpleDateFormat df = new SimpleDateFormat("dd:MM:yyyy"); 
   Date date = df.parse(dateRelease);
}catch (ParseException e) {} 

嗯,如果“dateRelease”的格式类型不正确,它会抛出 ParseException,但我想知道是否有人写成这样“40/03/2010” - 日、月或年无效范围错误。实际上,当发送无效日期时,SimpleDateFormat 只是创建一个具有默认数字的新日期。

我是否必须使用正则表达式创建自己的方法来处理它,或者是否存在告诉我要捕获的异常?

Is there a Date exception that I can deal with when I try to parse a date with this code here:

try{
   SimpleDateFormat df = new SimpleDateFormat("dd:MM:yyyy"); 
   Date date = df.parse(dateRelease);
}catch (ParseException e) {} 

Well, if the "dateRelease" isn't in a correct format type it throws ParseException, but I want to get if someone write like "40/03/2010" - WRONG with day, month or year invalid range. Actually, when a invalid date is sent, SimpleDateFormat just create a new Date with default numbers.

Do I have to create my own method with a regex to deal with it or is there an existing exception that tells me it to catch?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

日记撕了你也走了 2024-10-13 19:31:41

通过 < 使其变得不宽松code>SimpleDateFormat#setLenient(),值为 false

SimpleDateFormat df = new SimpleDateFormat("dd:MM:yyyy"); 
df.setLenient(false);
Date date = df.parse(dateRelease);

然后,当日期不在有效范围内时,它将抛出ParseException

Make it non-lenient by SimpleDateFormat#setLenient() with a value of false.

SimpleDateFormat df = new SimpleDateFormat("dd:MM:yyyy"); 
df.setLenient(false);
Date date = df.parse(dateRelease);

Then it will throw ParseException when the date is not in a valid range.

硬不硬你别怂 2024-10-13 19:31:41

tl;dr

try {
    LocalDate localDate = LocalDate.parse( 
        "40:03:2010" ,    // "40:03:2010" is bad input, "27:03:2010" is good input.
        DateTimeFormatter.ofPattern( "dd:MM:uuuu" )
    ) ;
} catch ( DateTimeParseException e ) {
    …  // Invalid input detected.
}

使用 java.time

现代方法是使用 Java 8 及更高版本中内置的 java.time 类。

您的示例数据与示例代码中显示的格式不匹配。一种使用 SOLIDUS(斜杠)字符,另一种使用冒号字符。我会选择冒号。

DateTimeFormatter

定义格式模式以匹配输入字符串。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd:MM:uuuu" );

LocalDate

解析为 LocalDate 对象,因为输入没有时间和时区。

LocalDate localDateGood = LocalDate.parse( "27:03:2010" , f );
System.out.println( "localDateGood: " + localDateGood );

现在尝试一些错误的输入。捕获适当的异常。

try {
    LocalDate localDateBad = LocalDate.parse( "40:03:2010" , f );
} catch ( DateTimeParseException e ) {
    System.out.println( "ERROR - Bad input." );
}

请参阅在 IdeOne.com 中实时运行的代码

本地日期良好:2010-03-27

错误 - 输入错误。

ISO 8601

将日期时间值交换/存储为文本时,使用标准 ISO 8601 格式。标准格式合理、实用,易于不同文化背景的人们阅读,并且易于机器解析。

对于仅日期值,标准格式为 YYYY-MM-DD,例如 2010-03-27

java.time 类在解析/生成字符串时默认使用标准 ISO 8601 格式。因此根本不需要指定格式模式

LocalDate localDate = LocalDate.parse( "2010-03-27" );
String output = localDate.toString();  // 2010-03-27

关于 java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如java.util.Date, 日历, & ; SimpleDateFormat

Joda-Time 项目,现已在 维护模式,建议迁移到 java.time 类。

要了解更多信息,请参阅 Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范为 JSR 310

从哪里获取 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如 间隔YearWeek<代码>YearQuarter,以及更多

tl;dr

try {
    LocalDate localDate = LocalDate.parse( 
        "40:03:2010" ,    // "40:03:2010" is bad input, "27:03:2010" is good input.
        DateTimeFormatter.ofPattern( "dd:MM:uuuu" )
    ) ;
} catch ( DateTimeParseException e ) {
    …  // Invalid input detected.
}

Using java.time

The modern way is with the java.time classes built into Java 8 and later.

Your example data does not match the format shown in your example code. One uses SOLIDUS (slash) character, the other uses COLON character. I'll go with COLON.

DateTimeFormatter

Define a formatting pattern to match the input string.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd:MM:uuuu" );

LocalDate

Parse as a LocalDate object as the input has no time-of-day and no time zone.

LocalDate localDateGood = LocalDate.parse( "27:03:2010" , f );
System.out.println( "localDateGood: " + localDateGood );

Now try some bad input. Trap for the appropriate exception.

try {
    LocalDate localDateBad = LocalDate.parse( "40:03:2010" , f );
} catch ( DateTimeParseException e ) {
    System.out.println( "ERROR - Bad input." );
}

See this code run live in IdeOne.com.

localDateGood: 2010-03-27

ERROR - Bad input.

ISO 8601

Use standard ISO 8601 formats when exchanging/storing date-time values as text. The standard formats are sensible, practical, easily read by humans of various cultures, and easy for machines to parse.

For a date-only value the standard format is YYYY-MM-DD such as 2010-03-27.

The java.time classes use standard ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern at all.

LocalDate localDate = LocalDate.parse( "2010-03-27" );
String output = localDate.toString();  // 2010-03-27

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文