【问题标题】:android utc time conversion issueandroid UTC时间转换问题
【发布时间】:2017-04-24 05:06:27
【问题描述】:

我需要将 UTC 时间字符串转换为我的本地时间,当我在 Eclipse 上运行该代码时,该代码在我的 PC 上运行良好,但是,我得到不正确的结果在 Android 上。我卡住了,谁能帮忙。

下面是我正在使用的代码,示例输入是“2017-04-24 1:00 AM”,这将产生“11:00 AM”,这是我所期待的,但是,它总是在 Android 上返回“10:00 AM”。

public String convertUTCTime(String utcTime) {

    Calendar cal = Calendar.getInstance();
    TimeZone tz = cal.getTimeZone();

    SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm a");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    try {
        Date date = sdf.parse(utcTime);
        sdf = new SimpleDateFormat("HH:mm a");
        sdf.setTimeZone(tz);
        String format = sdf.format(date);
        return format;
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return "Not applicable";
}

【问题讨论】:

  • 您是否正在考虑节约日光的可能性?
  • @james Use valid date format to parse date you are using 24 hours format with ap/pm it not valid check developer.android.com/reference/java/text/SimpleDateFormat.html link for your understand.
  • 请将 yyyy-MM-dd HH:mm a 替换为 yyyy-MM-dd hh:mm a 这将为您提供有效结果
  • HH:mm 代表 24 小时格式,hh:mm 代表 12 小时格式
  • 您的电脑在哪个时区运行?你的安卓设备呢?您可能想打印出tz 并研究其中的差异。它的toString 方法产生了一种有趣的格式,但如果你努力尝试,其中一些是可读的,并且无论如何你可以判断它在两种设备上是否相同。

标签: java android datetime utc


【解决方案1】:

看我准备的函数:-

public static String getUTCDate(String timestamp, String DateFormat) {
        SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm aa", Locale.getDefault());
        originalFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        SimpleDateFormat targetFormat = new SimpleDateFormat(DateFormat, Locale.getDefault());
        targetFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date date = null;
        String formattedDate = null;
        try {
            date = originalFormat.parse(timestamp);
            formattedDate = targetFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return formattedDate;
    }

通过调用获取值-

Utils.getUTCDate("2017-04-24 01:00 AM", "HH:mm a")

【讨论】:

  • 嘿,谢谢你的回答,但是你的方法对我不起作用,我仍然得到错误的输出。
  • 给我你的意见。确保您的输入是 2017-04-24 01:00 AM 而不是 2017-04-24 1:00 AM
  • 我已将输入硬编码为“2017-04-24 01:00 AM”,它仍然在 android 中返回“10:00 am”,但在我的 PC 上工作正常。
  • 还是不行,你的代码和我用的很相似,在PC上没问题,但在Android上总是返回“10:00 am”。
  • 我认为 Piyush Patel 的评论在这里也有效:当你有 am/pm 标记时,你可能更喜欢 hh 从 1 到 12 的小时而不是大写的 HH 从 0 到 23 的小时。
猜你喜欢
  • 1970-01-01
  • 2011-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-12
  • 2015-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多