当str = 2011/12/12aaaaaaaaaaa时,SimpleDateFormat parse(string str)不会引发异常?

编程入门 行业动态 更新时间:2024-10-25 20:22:48
本文介绍了当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)不会引发异常?

本文发布于:2023-10-31 05:11:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545101.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常   str   aaaaaaaaaaa   string   parse

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!