【问题标题】:shows Unparseable date: "09:30 AM" (at offset 6) in java android [duplicate]在java android中显示无法解析的日期:“09:30 AM”(偏移量6)[重复]
【发布时间】:2017-12-29 05:30:51
【问题描述】:

当我将参数传递为“09:30 AM”时,它会在 android 中返回异常 显示无法解析的日期:“09:30 AM”(偏移量 6)

 public static String convertTo24Hour (String now){
        String time24="";
          try {
            SimpleDateFormat inFormat = new SimpleDateFormat("hh:mm a");
            SimpleDateFormat outFormat = new SimpleDateFormat("HH:mm");
            time24 = outFormat.format(inFormat.parse(now));
        } catch (Exception e) {
            System.out.println("Exception : " + e.getMessage());
        }
        return time24;
    }

【问题讨论】:

  • 使用正确的语言环境。
  • 你确定你没有遗漏任何东西吗?因为代码看起来不错。尝试分配 Locale 。
  • 代码正确,显示完整的异常日志。
  • 顺便说一句,即使在 Android 上,也可以考虑扔掉长期过时且臭名昭著的麻烦 SimpleDateFormat 和朋友,并将 ThreeTenABP 添加到您的项目中,以便使用现代 Java 日期 java.time和时间 API。使用起来感觉好多了。

标签: java android


【解决方案1】:

试试这个

public static String convertTo24Hour (String now){
    String time24="";
    try {
        SimpleDateFormat inFormat = new SimpleDateFormat("hh:mm a",Locale.getDefault());
        SimpleDateFormat outFormat = new SimpleDateFormat("H:mm", Locale.getDefault());
        time24 = outFormat.format(inFormat.parse(now));
    } catch (Exception e) {
        System.out.println("Exception : " + e.getMessage());
    }
    return time24;
}

根据您的需要更改区域设置。 希望这会有所帮助..

【讨论】:

  • 同样的异常 :(
  • 这有什么帮助? SimpleDateFormat 如果您不指定,则已使用默认语言环境。
  • @Tom 我只是将其设置为默认值,因为我不知道他的语言环境。他必须根据自己的需要进行更改。
  • @shamasudheen 我已经尝试过这段代码。及其工作。只需用这个替换整个函数。
  • 你显然不需要他/她的语言环境,你需要设置一个接受“am”作为日期字符串一部分的语言环境(可以是固定的)。但是让我们假设您知道,您至少应该告诉 OP 他需要调整该值。 “试试这个”并不表明这一点。
猜你喜欢
  • 2017-11-19
  • 1970-01-01
  • 2016-03-18
  • 2018-01-08
  • 2015-10-31
  • 2017-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多