开发者

How can java SimpleDateFormat parse this - '3/31/09 10:04 AM()(*&*^%%^$'?

I'm doing some simple validation using SimpleDateFormat, it works fine, except one thing: When value like '3/31/09 10:04 AM()(&^%%^$' is passed to it no ParseException is thrown. It simply ignores th开发者_运维技巧at suffix/end . Is there a way to make it throw ParseException for such inputs?

Thanks in advance!


You can check whether the formatted date matches.

SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yy h:mm a");
Date date = sdf.parse(t);
String t2 = sdf.format(date);
if (!t2.equals(t))
    throw new ParseException("Not an exact match '" + t2 + "' != '" + t + "'", 0);

if you just want to check for trailing text

if (!t.endsWith("M"))
    throw new ParseException("Invalid format '" + t + "'", 0);


Try calling setLenient(false)

Specify whether or not date/time parsing is to be lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format. With strict parsing, inputs must match this object's format.

Also take a peek at javadocs for parse with some emphasis added (mine)...

The method attempts to parse text starting at the index given by pos. If parsing succeeds, then the index of pos is updated to the index after the last character used (parsing does not necessarily use all characters up to the end of the string), and the parsed date is returned. The updated pos can be used to indicate the starting point for the next call to this method. If an error occurs, then the index of pos is not changed, the error index of pos is set to the index of the character where the error occurred, and null is returned.

So, you need to check the index pos and possibly the error pos as well. Something like...

if (pos.getIndex() == input.length()) { /* all looks good */
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜