本文介绍了java.util.Date对象是否验证日期有效性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚写了这个单元测试:

I just wrote this unit tests :

@Test
public void testGetDateFromString() throws ParseException{
    String date = "52/29/2500";
    Date dateFromString = DateHelper.getDateFromString(date, DateHelper.DD_MM_YYYY_FORMAT);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DateHelper.DD_MM_YYYY_FORMAT);
    Date dateWithSimpleFormat = simpleDateFormat.parse(date);

    Assert.assertNotNull(dateFromString);
    Assert.assertNotNull(dateWithSimpleFormat);

    Assert.assertTrue(dateFromString.equals(dateWithSimpleFormat));

    System.out.println("dateFromString " + dateFromString);
    System.out.println("dateWithSimpleFormat " + dateWithSimpleFormat);
}

输出为:

dateFromString Wed Jun 21 00:00:00 CEST 2502
dateWithSimpleFormat Wed Jun 21 00:00:00 CEST 2502

DateHelper.DD_MM_YYYY_FORMAT 模式是 dd / MM / yyyy getDateFromString 是一个使用 commons-lang 库将String日期解析为Date对象的方法。

The DateHelper.DD_MM_YYYY_FORMAT pattern is dd/MM/yyyy and getDateFromString is a method that parses a String date to a Date object using commons-lang library.

为什么java.util.Date对象验证日期的有效性?

Why des the java.util.Date object verifies the date validity?

推荐答案

你需要设置 simpleDateFormat.setLenient(false); to使SimpleDateFormat严格验证您的输入。

You need to set simpleDateFormat.setLenient(false); to make the SimpleDateFormat to validate your input strictly.

您可以参考以进一步理解。根据定义,

You can refer the setLenient documentation for further understanding. By the definition,

Specify whether or not date/time parsing is to be lenient. With lenient parsing, 
the parser may use heuristics to interpret inputs that do not precisely match this 
object's format. With strict parsing, inputs must match this object's format.

这篇关于java.util.Date对象是否验证日期有效性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 23:48