android utc时间转换问题

时间:2017-04-24 05:06:28

标签: java android datetime utc

我需要将 UTC 时间字符串转换为我当地的时间,当我在 Eclipse 上运行时,我的电脑上的代码运行正常,但是,我得到的结果不正确在 Android 上。我被困住,有人可以帮忙。

下面是我正在使用的代码,示例输入将是" 2017-04-24 1:00 AM ",这将产生&#34的结果; 上午11:00 "这是我所期待的,然而,它总是回归" 10:00 AM "在Android上。

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";
}

1 个答案:

答案 0 :(得分:0)

看看我准备的功能: -

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")
相关问题