使用dateformat验证日期 [英] validating a date using dateformat

查看:109
本文介绍了使用dateformat验证日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证实际上是一个字符串的日期,并尝试以 yyyy / MM / dd 格式进行打印。
这是代码。

I am trying to validate a date which is actually a string, trying to print it in yyyy/MM/dd format. Here is the code.

String s="2012/12/0390990";
SimpleDateFormat ft = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(ft.format(ft.parse(s))); 

,输出为 3083/05/30 。我也想要验证。不知道如何进行。

and the output is 3083/05/30. I want to have the validations too. No clue how to proceed.

推荐答案

默认情况下宽松。您需要将其设置为非。

It's by default lenient. You need to set it non-lenient before parsing.

ft.setLenient(false);

这将导致 ParseException 与年份相比,提供了无效的日期和/或月份。请注意,这并不能验证年份本身,因为基本上任何年份都是有效的。根据具体的功能要求,您可能需要对年份进行其他检查,例如在 / 上分割字符串,然后检查第一部分的长度是否为4。

This will result in a ParseException when an invalid day and/or month is been supplied as compared to the year. Note that this doesn't validate the year itself as basically any number of years is valid. Depending on the concrete functional requirement, you might want to do an additional check on the year, e.g. split string on / and then check if the length of the 1st part is 4.

这篇关于使用dateformat验证日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆