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!