时间转换毫秒本地时间到毫秒 UTC 时间 android

Time conversion milliseconds local time to milliseconds UTC time in android

我的设备有 毫秒 的当前时间。

现在我需要将其转换为 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 毫秒本地时区毫秒

请给我一些建议。

关于您的代码的一些观察:

  • 您将格式化程序设置为 UTC,因此您将时间参数解释为 UTC,而不是 "local milliseconds",如 sdf.format(new Date(time)));.

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

我不知道你从哪里得到时间参数。但是你说这是要解释为 "local milliseconds" 的说法似乎是基于一种误解。在 UTC 时间轴 上处理 全局有效 instants/moments 时,测量即时时间的位置无关紧要(将时钟故障放在一边)。因此,时间参数可能已通过 System.currentTimeMillis() 等测量为设备时间,但您可以直接将其与任何其他时刻(甚至在其他设备上)进行比较,而无需进行任何转换。

如果你真的有 "local milliseconds"(不应该在专用时区库之外的 public 中处理),那么你需要一个时区偏移量来处理转换,否则就是任意猜测.这种转换的公式是伪代码:

[utc-time] = [local-time] minus [zone offset]

本地到 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 到本地

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

谢谢,我得到了这个解决方案