104

我想以毫秒为单位获取当前的 UTC 时间。我搜索了谷歌并得到了一些 System.currentTimeMillis() 确实返回 UTC 时间的答案。但事实并非如此。如果我执行以下操作:

long t1 = System.currentTimeMillis();
long t2 = new Date().getTime();
long t3 = Calendar.getInstance().getTimeInMillis();

所有三个时间几乎相同(由于调用,差异以毫秒为单位)。

t1 = 1372060916
t2 = 1372060917
t3 = 1372060918

这个时间不是 UTC 时间,而是我的时区时间。如何在android中获取当前的UTC时间?

4

2 回答 2

150

您显示的所有三行都将给出自 unix 纪元以来的毫秒数,这是一个固定的时间点,不受您当地时区的影响。

你说“这个时间不是 UTC 时间”——我怀疑你实际上是错误地诊断出来的。我建议为此使用epochconverter.com。例如,在您的示例中:

1372060916 = Mon, 24 Jun 2013 08:01:56 GMT

我们不知道您何时生成该值,但除非它实际上是在 UTC 上午 8:01,否则您的系统时钟有问题。

System.currentTimeMillisa 本身和 a 本身的值都Date不受时区的影响。但是,您应该知道它Date.toString() 确实使用了本地时区,这会误导许多开发人员认为 aDate与时区固有地相关联 - 它不是,它只是一个瞬间,没有关联的时区甚至日历系统。

于 2013-06-24T08:37:27.743 回答
2

I can confirm that all three calls could depend on the local time, considering the epoch, not the Date.toString() or any similar method. I've seen them depend on local time in specific devices running Android 2.3. I haven't tested them with other devices and android versions. In this case, the local time was set manually.

The only reliable way to get an independent UTC time is requesting a location update using the GPS_PROVIDER. The getTime() value of a location retrieved from NETWORK_PROVIDER also depends on local time. Another option is ping a server that returns a UTC timestamp, for example.

So, what I do is the following:

public static String getUTCstring(Location location) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    String date = sdf.format(new Date(location.getTime()));
    // Append the string "UTC" to the date
    if(!date.contains("UTC")) {
        date += " UTC";
    }
    return date;
}
于 2013-11-05T14:11:07.897 回答