在安卓中,将毫秒级别的本地时间转换成毫秒级别的UTC时间

3

我有设备当前时间的毫秒

现在我需要将它转换为UTC时区的毫秒数

于是我尝试了以下方法,但它未能将其转换为毫秒数。

public static long localToUTC(long time) {
    try {
        SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        Log.e("* UTC : " + time, " - " + sdf.format(new Date(time)));
        Date date = sdf.parse(sdf.format(new Date(time)));
        long timeInMilliseconds = date.getTime();
        Log.e("Millis in UTC", timeInMilliseconds + "" + new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a").format(date));
        return timeInMilliseconds;
    } catch (Exception e) {
        Log.e("Exception", "" + e.getMessage());
    }
    return time;
}

同样适用于UTC毫秒到本地时区毫秒的转换。

请给我一些建议。


代码看起来没问题。你确定你在正确地测试它吗?也许你可以添加一些样例输入和期望输出。 - s7vr
谢谢,我已经测试过了,它给了我正确的日期,但是当我从日期对象中获取毫秒数时,long timeInMilliseconds = date.getTime(); 它给了我一些不准确的值,而我需要的是准确的值。 - Amjad Khan
2个回答

6

对于本地时间和UTC时间的毫秒转换

本地时间转UTC时间

public static long localToUTC(long time) {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
            Date date = new Date(time);
            dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            String strDate = dateFormat.format(date);
//            System.out.println("Local Millis * " + date.getTime() + "  ---UTC time  " + strDate);//correct

            SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
            Date utcDate = dateFormatLocal.parse(strDate);
//            System.out.println("UTC Millis * " + utcDate.getTime() + " ------  " + dateFormatLocal.format(utcDate));
            long utcMillis = utcDate.getTime();
            return utcMillis;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return time;
    }

对于UTC TO LOCAL的转换

public static long utcToLocal(long utcTime) {
        try {
            Time timeFormat = new Time();
            timeFormat.set(utcTime + TimeZone.getDefault().getOffset(utcTime));
            return timeFormat.toMillis(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return utcTime;
    }

谢谢,我明白了这个解决方案。


1

关于您的代码,有以下一些观察:

  • 您将格式化程序设置为UTC,因此将时间参数解释为UTC,而不是像sdf.format(new Date(time)));中所做的那样解释为“本地毫秒”。

  • Date date = sdf.parse(sdf.format(new Date(time))); 没有任何意义。您可以无需进行格式化和解析而直接编写:Date date = new Date(time);

我不知道您从哪里获取时间参数。但是,您的说法这应该被解释为“本地毫秒”似乎是基于误解的。当处理UTC时间线上的全球有效瞬间/时刻时,测量瞬间时间的位置(除了时钟故障)是无关紧要的。因此,时间参数可能已通过System.currentTimeMillis()等方式测量为设备时间,但是您可以直接将其与任何其他瞬间(甚至在其他设备上)进行比较,而无需进行转换。

如果您真的有“本地毫秒”(不应在专用时区库之外的公共场合处理),则需要时区偏移来处理转换,否则就是随意的猜测。这种转换的公式将以伪代码形式呈现:

[utc-time] = [local-time] 减去 [时区偏移量]

谢谢,我找到了解决方案,解决了一些错误。 - Amjad Khan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接