【问题标题】:Error when trying to convert String to Datetime in Android尝试在 Android 中将字符串转换为日期时间时出错
【发布时间】:2015-09-28 16:52:54
【问题描述】:

我是 Android 新手,对此有疑问。我想将此日期时间字符串“EEE MMM dd HH:mm:ss Z yyyy”转换为“HH:mm”。这是我的字符串:

String date = "Mon Sep 28 19:49:26 GMT+07:00 2015";

我曾尝试像这样转换它,但它失败了,我看不到是什么异常,因为Exception e 始终为空!

private String convertDate(String date) {
    try {
        SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
        Date d = format.parse(date);
        SimpleDateFormat serverFormat = new SimpleDateFormat("HH:mm");
        return serverFormat.format(d);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

那么我怎样才能得到 "HH:mm" 或者我怎样才能转换它呢?我的转换功能有什么问题吗?

【问题讨论】:

  • Exception e 怎么可能总是为空?这将引发另一个NullPointerException
  • 我尝试同时使用 ParseException 和 Exception。但是当我使用断点查看发生了什么时,它总是为空!
  • 也许你是对的。当我们转换日期时间时,似乎 Android 会强制我们确定语言环境

标签: java android date datetime


【解决方案1】:

语言环境

将您的Locale 设置为Locale.ENGLISH

    ... = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH);

    ... = new SimpleDateFormat("HH:mm", Locale.ENGLISH);

【讨论】:

  • 哇!终于成功了,非常感谢!你刚刚拯救了我的大脑。哈哈
  • 但我想知道当我在eclipse中实现这个方法时它工作正常。为什么我不能在 Java Android 中?
  • 我不确定,但我猜当 Eclipse PC 使用 ENGLISH local 作为 defulat 时,Android 有自己的本地区域 - 只是猜测
  • 我也这么认为。但是 StackOverFlow 中的许多问题与我的问题相同,但他们没有提到 Locale。他们只是在控制台结果中提供解决方案,而不是在 Android 应用程序中。这让我非常非常困惑
  • @JustinVăn 您可能会发现这个问题When is Locale needed for parsing date-time strings in Java? 提供了丰富的信息。
猜你喜欢
  • 1970-01-01
  • 2020-10-13
  • 2022-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-14
相关资源
最近更新 更多