当str = 2011/12/12aaaaaaaaaaa时,SimpleDateFormat parse(string str)不会引发异常? [英] SimpleDateFormat parse(string str) doesn't throw an exception when str = 2011/12/12aaaaaaaaa?

查看:74
本文介绍了当str = 2011/12/12aaaaaaaaaaa时,SimpleDateFormat parse(string str)不会引发异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是一个例子:

public MyDate() throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
    sdf.setLenient(false);
    String t1 = "2011/12/12aaa";
    System.out.println(sdf.parse(t1));
}

2011/12/12aaa不是有效的日期字符串.但是,该函数将打印"PST 2011 Mon Dec 12 00:00:00 PST 2011",并且不会引发ParseException.

2011/12/12aaa is not a valid date string. However the function prints "Mon Dec 12 00:00:00 PST 2011" and ParseException isn't thrown.

有人可以告诉我如何让SimpleDateFormat将"2011/12/12aaa"视为无效的日期字符串并引发异常吗?

Can anyone tell me how to let SimpleDateFormat treat "2011/12/12aaa" as an invalid date string and throw an exception?

推荐答案

parse(...)上的JavaDoc声明以下内容:

The JavaDoc on parse(...) states the following:

解析并不一定要使用直到字符串末尾的所有字符

parsing does not necessarily use all characters up to the end of the string

似乎您无法使SimpleDateFormat引发异常,但是您可以执行以下操作:

It seems like you can't make SimpleDateFormat throw an exception, but you can do the following:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
sdf.setLenient(false);
ParsePosition p = new ParsePosition( 0 );
String t1 = "2011/12/12aaa";    
System.out.println(sdf.parse(t1,p));

if(p.getIndex() < t1.length()) {
  throw new ParseException( t1, p.getIndex() );
}

基本上,您检查解析是否消耗了整个字符串,如果不是,则输入无效.

Basically, you check whether the parse consumed the entire string and if not you have invalid input.

这篇关于当str = 2011/12/12aaaaaaaaaaa时,SimpleDateFormat parse(string str)不会引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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