你知道怎样利用 SimpleDateFormat 验证日期格式
本文将介绍怎样利用 SimpleDateFormat 验证日期格式,日期格式是否符合预期格式。
在 Java 中,您可以使用 SimpleDateFormat 类来验证日期字符串是否符合特定的格式。以下是一个简单例子:
import java.text.SimpleDateFormat;
public class Demo {
public static void main(String[] args) throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("case1: " + dateFormat.format(dateFormat.parse("2024-01-22 13:42:17")));
System.out.println("case2: " + dateFormat.format(dateFormat.parse("2024-01-22 13:42:1700")));
System.out.println("case3: " + dateFormat.format(dateFormat.parse("2024-01-22 13:42:17hello")));
System.out.println("case4: " + dateFormat.format(dateFormat.parse("2024-01-22 13:142:17")));
System.out.println("case5: " + dateFormat.format(dateFormat.parse("2024-1-22 13:42:17")));
}
}运行示例,输出如下:
case1: 2024-01-22 13:42:17
case2: 2024-01-22 14:10:20
case3: 2024-01-22 13:42:17
case4: 2024-01-22 15:22:17
case5: 2024-01-22 13:42:17根据输出可知,即使我们的日期格式存在问题,SimpleDateFormat 默认情况下也会很好的宽松解析,显然这对我们验证日期格式是不允许的。
此时,我们可以通过将 setLenient() 方法将验证设置为严格模式,方法定义如下:
public void setLenient(boolean lenient)
指定日期/时间解析是否宽松。通过宽泛的解析,解析器可以使用启发式来解释不精确匹配该对象格式的输入。通过严格的解析,输入必须与此对象的格式相匹配。
此方法等同于以下调用。
getCalendar().setLenient(lenient)
参数:
lenient - 当为 true ,解析是宽松的;当为 false,解析是严格的;
以下示例将 SimpleDateFormat 解析设置为严格模式:
import java.text.SimpleDateFormat;
public class Demo {
public static void main(String[] args) throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 设置为严格模式,不允许解析不严格的日期
dateFormat.setLenient(false);
System.out.println("case1: " + dateFormat.format(dateFormat.parse("2024-01-22 13:42:17")));
System.out.println("case2: " + dateFormat.format(dateFormat.parse("2024-01-22 13:42:1700")));
System.out.println("case3: " + dateFormat.format(dateFormat.parse("2024-01-22 13:42:17hello")));
System.out.println("case4: " + dateFormat.format(dateFormat.parse("2024-01-22 13:142:17")));
System.out.println("case5: " + dateFormat.format(dateFormat.parse("2024-1-22 13:42:17")));
}
}运行示例,输出如下:
case1: 2024-01-22 13:42:17
Exception in thread "main" java.text.ParseException: Unparseable date: "2024-01-22 13:42:1700"
at java.text.DateFormat.parse(DateFormat.java:366)
at com.hxstrive.Demo.main(Demo.java:13)上面输出可知,只有日期字符串和日期格式完全匹配才会解析,否则抛出 java.text.ParseException 异常。
学习从来无捷径,循序渐进登高峰。 —— 高永祚
说说我的看法 -
还可使用 Gitee / GitHub 账号一键登录,与大家分享你的观点
立即登录
全部评论()
没有评论
- Java语法速查笔记:快速掌握90%日常开发语法点
- Readable 接口:用于定义一个可以被读取的对象
- Iterable 接口:是 Java 中用于实现迭代功能的基础接口
- Java 中自己的业务方法返回自己的 Feture,如何实现?
- Comparable 接口:用于定义对象的自然排序顺序
- Cloneable 接口:一个标记接口,表明一个类可以被克隆
- CharSequence 接口:用于表示可读的字符序列
- AutoCloseable 接口:为了支持资源的自动管理
- Appendable 接口:用于向字符序列添加字符或字符序列
- JDK8“? extends T”和“? super T”泛型通配符