gpt4 book ai didi

java - 在 Java 中将字符串解析为日期时出错

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

是的,另一个 Java Date 帖子 :)

我的问题:

简单的标准代码,用于测试插入的日期是否符合要求的格式 (dd/MM/yyyy):

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {

sdf.parse(strDate);

} catch(ParseException e) {

// err

}

strDate = "10-12-2012" ----> sysout = err (ok)

strDate = "2012-11-10" ----> sysout = err (ok)

strDate = "15/10/2011" ----> sysout = parse (ok)

问题:

strDate = "2012/12/15" ----> sysout = this date that i expect an error result parsed like "Tue Jun 03 00:00:00 CET 21"

谁知道???

最佳答案

只需设置setLenient

来自 API:

setLenient method:

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.

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
sdf.setLenient(false);
System.out.println(sdf.parse("2012/12/15"));
} catch(ParseException e) {
e.printStackTrace();
}

关于java - 在 Java 中将字符串解析为日期时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13531512/

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