[Java date Processing] judge whether the date is valid (loose: Non-lenient Mode)

Source: Internet
Author: User

Function: Check whether the date is valid (mainly to determine whether the validity of a month's date exceeds the maximum date of the month)
Test data: 20070229 false
20070228 false
20040229 true

/**
* Check if the date is valid
*
* @ Param date the date to be checked
* @ Return: whether the date is valid
*/
Public static Boolean chkdateformat (string date ){
Try {
// If the input date is not 8 bits, the value is false.
If (null = date | "". Equals (date) |! Date. Matches ("[0-9] {8 }")){
Return false;
}
Int year = integer. parseint (date. substring (0, 4 ));
Int month = integer. parseint (date. substring (4, 6)-1;
Int day = integer. parseint (date. substring (6 ));
Calendar calendar = gregoriancalendar. getinstance ();
// When the calendar is in non-lenient mode, if any inconsistency exists in the calendar field, it throws an exception.
Calendar. setlenient (false );
Calendar. Set (calendar. year, year );
Calendar. Set (calendar. Month, month );
Calendar. Set (calendar. Date, Day );
// If the date is incorrect, an exception is thrown when this statement is executed.
Calendar. Get (calendar. year );
} Catch (illegalargumentexception e ){
Return false;
}
Return true;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.