【问题标题】:SimpleDateFormat - Unparsable Date exception with IST timezone. What's wrong?SimpleDateFormat - IST 时区的不可解析日期异常。怎么了?
【发布时间】:2015-10-28 12:02:08
【问题描述】:

我有该格式的日期字符串:

Oct 28, 2015, 05.15PM IST

所以我想使用 SimpleDateFormat 将其解析为 Date 对象:

String date = "Oct 28, 2015, 05.15PM IST";
SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy, hh.mmaa zzz", Locale.US);
Date myDate = format.parse(date);

但我得到了例外:

java.text.ParseException: Unparseable date: "Oct 28, 2015, 05.15PM IST" (at offset 22)

我做错了什么?

【问题讨论】:

  • 根据给定的代码,它可以工作here
  • @sam 我很困惑。在我的代码中,它仍然会引发异常。
  • 检查Java: unparseable date exception。这是一个类似的问题
  • @sam 好的,好像我没有“IST”ID。但是我怎么能这样处理呢?
  • 这是由时区“IST”中的歧义引起的。见this question

标签: java simpledateformat


【解决方案1】:

根据我对SimpleDateFormat的理解,在指定 AM/PM 组件时,您不需要使用两个 a 或三个 z。您正在尝试使用多个 AM/PM 说明符以及多个时区说明符来解析“2015 年 10 月 28 日,05.15PM IST”。将格式对象更改为SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy, hh.mma z", Locale.US);

【讨论】:

    【解决方案2】:

    问题在于 SimpleDateFormat 无法将“IST”解析为时区,因为它不明确。

    我根据 Adriaan Koster's answer 解决了这个问题。 但实际上它只有在我从日期字符串中删除“IST”之后才对我有用。 所以问题的完整解决方案如下所示:

    String date = "Oct 28, 2015, 05.15PM IST";
    date = date.substring(0, date.length()-4);
    
    SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy, hh.mma", Locale.US);
    format.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
    Date myDate = format.parse(date);
    

    【讨论】:

      猜你喜欢
      • 2019-12-04
      • 1970-01-01
      • 2020-10-11
      • 2011-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多