Whether a Java string conforms to the date format

Source: Internet
Author: User

Java beginners often encounter problems and there are many online solutions. In my opinion, there are two simple and practical methods:

1) convert the string parse to the date type, and then convert the format to the string type to compare it with the original string.Relatively strict, similar to does not meet the requirements!

Public   Class Dateformat {
Public   Static   Void Main (string [] ARGs ){
Simpledateformat FMT =   New Simpledateformat ( " Yyyy-mm-dd " );
String s =   " 02-02-2009 " ;
Date = FMT. parse (s );
System. Out. println (FMT. Format (date). Equals (s ));
}
}

 

2) use setlenient () directly ().However, this method has limitations. It can still be normal at 02-02-02!

Public   Class Dateformat {
Public   Static   Void Main (string [] ARGs ){
Simpledateformat FMT =   New Simpledateformat ( " Yyyy-mm-dd " );
// When lenient-is true, the analysis process is not strict.
FMT. setlenient ( False );
String s =   " 02-02-2009 " ;
Try {
Date = FMT. parse (s );
} Catch (Parseexception e ){
E. printstacktrace ();
}
}

 

It is said that regular expressions are the most efficient. You have time to add them!

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.