首页 > 解决方案 > 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"));

但是日期仍然显示在未来,这是不正确的。如何正确解析此日期?谢谢你。

标签: javasimpledateformat

解决方案


不要使用 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

推荐阅读