java - SimpleDateFormat 不解析 IST 日期
问题描述
我正在尝试解析这个日期:星期一,2021 年 7 月 5 日 23:19:58 IST
String date = "Mon, 05 Jul 2021 23:19:58 IST";
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.getDefault());
dateFormat.parse(date);
但我收到了这个错误:java.text.ParseException: Unparseable date: "Mon, 05 Jul 2021 23:19:58 IST"
当我从格式中省略小写 z 时,我没有得到异常,但日期不在正确的时区。我尝试过执行以下操作:
dateFormat.setTimeZone(TimeZone.getTimeZone("IST"));
但是日期仍然显示在未来,这是不正确的。如何正确解析此日期?谢谢你。
解决方案
不要使用 Date 或 SimpleDateTime。使用 java.time 包中的类。
String date = "Mon, 05 Jul 2021 23:19:58 IST";
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(
"EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
ZonedDateTime zdt = ZonedDateTime.parse(date,dateFormat);
System.out.println(zdt.format(dateFormat));
印刷
Mon, 05 Jul 2021 23:19:58 GMT
编辑
仔细阅读java.time
包裹后,我发现其中ZoneId.SHORT_IDS
包含IST=Asia/Kolkata
. 因此,如果执行以下操作:
ZonedDateTime zdt = ZonedDateTime.parse(date,dateFormat)
.withZoneSameLocal(ZoneId.of("Asia/Kolkata"));
System.out.println(zdt.format(dateFormat));
它打印
Mon, 05 Jul 2021 23:19:58 IST
推荐阅读
- node.js - 在win10中,我执行yarn add protobufjs,但是报错:error An unexpected error occurred: "EPERM: operation not allowed, unlink
- python - 模型很容易收敛但预测结果很差
- java - 尽管没有任何错误,但 JDBC 无法更新
- regex - 正则表达式:匹配带有下划线和 id 的单词
- perl - 如何将多个 HMTL 文件中的内容合并到一个文件中?
- http - 为什么不总是为 CORS 请求发送 Origin HTTP 标头?
- javascript - React cloneElement 不适用于功能组件
- java - 如何将参数注入 JUnit 5 扩展
- java - 如何查找数字序列是升序还是降序
- java - 使用 httpClient 创建 HttpComponentsMessageSender