gpt4 book ai didi

Java SimpleDateFormat 返回意外结果

转载 作者:太空狗 更新时间:2023-10-29 22:48:31 25 4
gpt4 key购买 nike

我正在尝试使用 Java 的 SimpleDateFormat 来使用以下代码解析 String to date。

public class DateTester {

public static void main(String[] args) throws ParseException {
String dateString = "2011-02-28";

SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");

System.out.println(dateFormat.parse(dateString));
}
}

我期待一些解析错误。但有趣的是,它会打印以下字符串。

Wed Jul 02 00:00:00 IST 195

无法解释。谁能帮忙?

谢谢

最佳答案

默认情况下,SimpleDateFormat 是宽松的,因此要使其失败,您需要执行以下操作:

dateFormat.setLenient( false ) ;

在解析日期之前。然后你会得到异常:

java.text.ParseException: Unparseable date: "2011-02-28"

关于Java SimpleDateFormat 返回意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6899019/

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