Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

java - 如何使用Java中的UTC或GMT获取当前日期和时间?(How can I get the current date and time in UTC or GMT in Java?)

When I create a new Date object, it is initialized to the current time but in the local timezone.

(当我创建一个新的Date对象时,它被初始化为当前时间,但是在本地时区。)

How can I get the current date and time in GMT?

(如何获取格林尼治标准时间的当前日期和时间?)

  ask by Behrang translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

java.util.Date has no specific time zone, although its value is most commonly thought of in relation to UTC.

(尽管java.util.Date的值通常与UTC有关,但没有特定的时区。)

What makes you think it's in local time?

(是什么让您认为这是当地时间?)

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.

(准确地说: java.util.Date的值是自Unix纪元以来的毫秒数,该纪元发生在UTC的1970年1月1日午夜。)

The same epoch could also be described in other time zones, but the traditional description is in terms of UTC.

(相同的纪元也可以在其他时区进行描述,但是传统的描述是以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.

(由于距固定纪元以来已有毫秒数,因此java.util.Date的值在世界各地在任何特定时刻都是相同的,而与本地时区无关。)

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.

(我怀疑问题在于您是通过使用本地时区的Calendar实例显示它,还是使用也使用本地时区的Date.toString()SimpleDateFormat实例(默认情况下也使用本地)来显示它时区。)

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

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

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

(但是,无论如何,我还是建议您使用Joda-Time ,它提供了更加清晰的API。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...