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

标签 android datetime timezone utc

我的设备有 MILLISECONDS 的当前时间。

现在我需要将其转换为 MILLISECONDS OF UTC TIME-ZONE

所以我试过了,但它不是以毫秒为单位的转换。

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 MILLISECONDLOCAL TIME ZONE MILLISECOND

请给我一些建议。

最佳答案

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

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

关于android - 时间转换毫秒本地时间到毫秒UTC时间在android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41062341/

相关文章:

python - 无法转换 Pandas 数据帧时间戳

android - java.lang.NoClassDefFoundError : com. instabug.library 错误

android - gradle android 插件和构建类型源集的问题

android - Android Canvas.drawBitmap 性能不佳 - 切换到 OpenGL?

php - 计算有特价的天数

java - 使用ZoneId得到的下拉列表太长,如何简化列表?

Android 重试/取消对话框

MySQL 使用带有日期文本的字符串列作为日期字段

sql - 仅在 SQL Server 的日期时间列中更新时间

Java 设置时区,同时将日期从山地转换为东部到格林威治标准时间