String s = 2001/11/11";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
try {
Date d = sdf.parse(s);
System.out.println("Good format");
}catch (ParseException pe){
System.out.println("Bad format");
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
try {
Date d = sdf.parse(s);
System.out.println("Good format");
}catch (ParseException pe){
System.out.println("Bad format");
}
例如,用户在画面上输入一个日期,我在程序中需要判断这个日期是否是真是一个日期。如果用户输入“2001/02/29”或是“2001/01/32”,并不时有效日期,我需要判断出来。
说白了,就是有些象VB中的isDate函数。不知道JAVA中有没有这样的函数。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
if (sdf.format(sdf.parse(tmp)).equalsIgnoreCase(tmp))
System.out.println("OK");
else
System.out.println("Err");
} catch (Exception ex) {
System.out.println("Err");
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
try {
if (sdf.format(sdf.parse(tmp)).equalsIgnoreCase(tmp))
System.out.println("OK");
else
System.out.println("Err");
} catch (Exception ex) {
System.out.println("Err");
}
于是就不用判断了。。
function validateUSDate( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
valid dates with 2 digit month, 2 digit day,
4 digit year. Date separator can be ., -, or /.
Uses combination of regular expressions and
string parsing to validate date.
Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy
PARAMETERS:
strValue - String to be tested for validity
RETURNS:
True if valid, otherwise false.
REMARKS:
Avoids some of the limitations of the Date.parse()
method such as the date separator character.
*************************************************/
var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
//check to see if in correct format
if(!objRegExp.test(strValue))
return false; //doesn't match pattern, bad date
else{
var strSeparator = strValue.substring(2,3) //find date separator
var arrayDate = strValue.split(strSeparator); //split date into month, day, year
//create a lookup for months not equal to Feb.
var arrayLookup = { '01' : 31,'03' : 31, '04' : 30,'05' : 31,'06' : 30,'07' : 31,
'08' : 31,'09' : 30,'10' : 31,'11' : 30,'12' : 31}
var intDay = parseInt(arrayDate[1]); //check if month value and day value agree
if(arrayLookup[arrayDate[0]] != null) {
if(intDay <= arrayLookup[arrayDate[0]] && intDay != 0)
return true; //found in lookup table, good date
}
//check for February
var intYear = parseInt(arrayDate[2]);
var intMonth = parseInt(arrayDate[0]);
if( ((intYear % 4 == 0 && intDay <= 29) || (intYear % 4 != 0 && intDay <=28)) && intDay !=0)
return true; //Feb. had valid number of days
}
return false; //any other values, bad date
}