import java.text.ParseException;
import java.text.SimpleDateFormat;
/**
* 校驗8位字符串是否為正確的日期格式
* @author 【J.H】
* 參考:https://blog.csdn.net/cc_yy_zh/article/details/73181010
*/
public class Demo1 {
//校驗8位字符串是否為正確的日期格式
private static boolean isValidDate(String str) {
boolean result = true;
//判斷字符串長度是否為8位
if(str.length() == 8){
// 指定日期格式為四位年/兩位月份/兩位日期,注意yyyy/MM/dd區分大小寫;
//SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
try {
// 設置lenient為false.
// 否則SimpleDateFormat會比較寬松地驗證日期,比如2007/02/29會被接受,並轉換成2007/03/01
format.setLenient(false);
format.parse(str);
} catch (ParseException e) {
// e.printStackTrace();
// 如果throw java.text.ParseException或者NullPointerException,就說明格式不對
result = false;
}
}else{
result = false;
}
return result;
}
public static void main(String[] args) {
String s = "2018042";
System.out.println(isValidDate(s));
}
}