2015-09-13 06:30:01
阅读( 643 )
下面例子使用SimpleDateFormat类的parse方法尝试解析字符串,若解析成功则说明字符串是合法的日期字符串,否则则说明输入的字符串不是合法的日期。
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class DateTest {
public boolean isValidDate(String inDate) {
if (inDate == null)
return false;
//set the format to use as a constructor argument
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
if (inDate.trim().length() != dateFormat.toPattern().length())
return false;
dateFormat.setLenient(false);
try {
//parse the inDate parameter
dateFormat.parse(inDate.trim());
}
catch (ParseException pe) {
return false;
}
return true;
}
public static void main(String[] args) {
DateTest test = new DateTest();
System.out.println(test.isValidDate("2004-02-29"));
System.out.println(test.isValidDate("2005-02-29"));
}
}
输出如下:
true
false
分享给朋友:
亲~ 如果您有更好的答案 可在评论区发表您独到的见解。
您想查看更多的信息:
面试题