有效日期格式检查 Java
Valid date format check in Java
当我执行以下代码时,即使我提供的日期不正确 (2010-55-04),我也会得到 'True'。谁能解释一下为什么会这样。
package basic;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class VerifyIfStrngIsValidDate {
public static boolean checkdate(String dt1)
{
SimpleDateFormat df1=new SimpleDateFormat("yyyy-mm-dd");
System.out.println(df1.toPattern());
df1.setLenient(false);
try {
df1.parse(dt1);
} catch (ParseException e) {
return false;
}
return true;
}
public static void main(String[] args) {
boolean res;
res=checkdate("2010-55-04");
System.out.println(res);
}
}
您对年-月-日使用了错误的格式掩码。使用 M
表示月,而不是 m
,即分钟:
SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
你会看到下面的演示在进行此更改后现在失败了。
当我执行以下代码时,即使我提供的日期不正确 (2010-55-04),我也会得到 'True'。谁能解释一下为什么会这样。
package basic;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class VerifyIfStrngIsValidDate {
public static boolean checkdate(String dt1)
{
SimpleDateFormat df1=new SimpleDateFormat("yyyy-mm-dd");
System.out.println(df1.toPattern());
df1.setLenient(false);
try {
df1.parse(dt1);
} catch (ParseException e) {
return false;
}
return true;
}
public static void main(String[] args) {
boolean res;
res=checkdate("2010-55-04");
System.out.println(res);
}
}
您对年-月-日使用了错误的格式掩码。使用 M
表示月,而不是 m
,即分钟:
SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
你会看到下面的演示在进行此更改后现在失败了。