gpt4 book ai didi

java - 当 str = 2011/12/12aaaaaaaaa 时,SimpleDateFormat parse(string str) 不会抛出异常?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:08:57 25 4
gpt4 key购买 nike

这是一个例子:

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 不是有效的日期字符串。但是,该函数会打印“Mon Dec 12 00:00:00 PST 2011”并且不会抛出 ParseException。

谁能告诉我如何让 SimpleDateFormat 将“2011/12/12aaa”视为无效日期字符串并抛出异常?

最佳答案

parse(...) 上的 JavaDoc 声明如下:

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

看起来你不能让 SimpleDateFormat 抛出异常,但你可以执行以下操作:

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() );
}

基本上,您检查解析是否消耗了整个字符串,如果没有,您的输入无效。

关于java - 当 str = 2011/12/12aaaaaaaaa 时,SimpleDateFormat parse(string str) 不会抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8428313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com