如何在 Java 中以 UTC 或 GMT 格式获取当前日期和时间? [英] How can I get the current date and time in UTC or GMT in Java?

查看:31
本文介绍了如何在 Java 中以 UTC 或 GMT 格式获取当前日期和时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我创建一个新的 Date 对象时,它被初始化为当前时间但在本地时区.如何获取格林威治标准时间的当前日期和时间?

When I create a new Date object, it is initialized to the current time but in the local timezone. How can I get the current date and time in GMT?

推荐答案

java.util.Date 没有特定的时区,尽管它的值最常被认为与 UTC 相关.是什么让你觉得现在是当地时间?

java.util.Date has no specific time zone, although its value is most commonly thought of in relation to UTC. What makes you think it's in local time?

准确地说:java.util.Date 中的值是自 Unix 纪元(UTC 时间 1970 年 1 月 1 日午夜)以来的毫秒数.同一个纪元也可以用其他时区来描述,但传统的描述是用 UTC 来描述的.由于它是自固定纪元以来的毫秒数,因此 java.util.Date 中的值在世界各地的任何特定时刻都是相同的,无论本地时区如何.

To be precise: the value within a java.util.Date is the number of milliseconds since the Unix epoch, which occurred at midnight January 1st 1970, UTC. The same epoch could also be described in other time zones, but the traditional description is in terms of UTC. As it's a number of milliseconds since a fixed epoch, the value within java.util.Date is the same around the world at any particular instant, regardless of local time zone.

我怀疑问题在于您通过使用本地时区的 Calendar 实例显示它,或者可能使用 Date.toString() 也使用本地时区,或者 Date.toString()code>SimpleDateFormat 实例,默认情况下也使用本地时区.

I suspect the problem is that you're displaying it via an instance of Calendar which uses the local timezone, or possibly using Date.toString() which also uses the local timezone, or a SimpleDateFormat instance, which, by default, also uses local timezone.

如果这不是问题,请发布一些示例代码.

If this isn't the problem, please post some sample code.

无论如何,我建议您使用 Joda-Time,它提供了更清晰的 API.

I would, however, recommend that you use Joda-Time anyway, which offers a much clearer API.

这篇关于如何在 Java 中以 UTC 或 GMT 格式获取当前日期和时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆