gpt4 book ai didi

java - 为什么 SimpleDateFormat setTimeZone 不会因无效时区而引发错误

转载 作者:行者123 更新时间:2023-12-02 08:40:33 26 4
gpt4 key购买 nike

我正在使用SimpleDateFormat将字符串类型的时间转换为unix时间戳,但是当我将时区设置为非法值时,我仍然得到正确的结果,SimpleDateFormat.parse()方法是如何定义的?如果我想进行单元测试来测试失败案例,我该怎么做?

String str = "2016-06-21-10-19-22";

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
df.setTimeZone(TimeZone.getTimeZone("fewfefewf"));

Date date = df.parse(str);

long epoch = date.getTime();
System.out.println(epoch);

最佳答案

因为getTimeZone如果无法理解指定的时区,则返回默认 GMT 时区的方法

the specified TimeZone, or the GMT zone if the given ID cannot be understood.

如果建议使用TimeZone.getAvailableIDs进行验证,并轻松检查以验证输入时区是否有效

Arrays.stream(TimeZone.getAvailableIDs()).anyMatch(tz->tz.equals("fewfefewf"))

最终推荐请使用j ava-8 date time api类并开始远离 SimpleDateFormat

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss"); // make sure you use H for hours in format

LocalDateTime dateTime = LocalDateTime.parse(str,formatter);

关于java - 为什么 SimpleDateFormat setTimeZone 不会因无效时区而引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61415185/

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