Java 如何使 date.getTime() 返回 UTC 时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2403109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:05:31  来源:igfitidea点击:

How to make date.getTime() returns UTC time?

javadateutc

提问by flyingfromchina

I have a Date object which represents a UTC time. When I use the method getTime() to get the long value of this object, the value returned corresponds to our local time (central US). What is the correct way to get the value back which corresponds to the original UTC time?

我有一个表示 UTC 时间的 Date 对象。当我使用 getTime() 方法获取此对象的 long 值时,返回的值对应于我们的本地时间(美国中部)。取回与原始 UTC 时间相对应的值的正确方法是什么?

Thanks

谢谢

回答by Matthew Flaschen

getTime()returns "the number of milliseconds since January 1, 1970, 00:00:00 GMT", nothing more, nothing less (obviously, you have to create it correctly). You can format it however you want, starting with e.g. the GregorianCalendar(TimeZone)constructor.

getTime()返回“自 1970 年 1 月 1 日以来的毫秒数,格林威治标准时间 00:00:00”,仅此而已(显然,您必须正确创建它)。您可以根据需要对其进行格式化,例如从GregorianCalendar(TimeZone)构造函数开始。

回答by Pops

The DateFormatclass has a method for setting your preferred time zone, and there's a time zone class that has a setting for UTC time.

DateFormat班有设置您的时区的方法,而且也具有时区类为UTC时间的设置

So, for example,

所以,例如,

SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC"));
Date yourUtcDate = sdf.parse(yourOriginalDate);

回答by Steve Kuo

java.util.Datehas no concept of timezone. It simply holds time relative to epoch, which is Jan 1 1970 00:00:00 UTC. Date is a model, separate from the view. When you display the date, the concept of timezone then is applied. Date's toString() displays a human readable date in the default timezone. You can either use a DateFormatto display a Date in a different timezone (such as UTC), or change the JVM's default timezone.

java.util.Date没有时区的概念。它只是保存相对于纪元的时间,即 1970 年 1 月 1 日 00:00:00 UTC。日期是一个模型,与视图分开。当您显示日期时,就会应用时区的概念。Date 的 toString() 在默认时区中显示人类可读的日期。您可以使用 aDateFormat来显示不同时区(例如 UTC)中的日期,或者更改 JVM 的默认时区。

回答by Basil Bourque

tl;dr

tl;博士

Instant.now()

…and…

…和…

Instant.ofEpochMilli( n ) 

…and…

…和…

instant.toEpochMilli()

Dateis always in UTC

Date总是在 UTC

When I use the method getTime() to get the long value of this object, the value returned corresponds to our local time (central US).

当我使用 getTime() 方法获取此对象的 long 值时,返回的值对应于我们的本地时间(美国中部)。

No, the value returned from Date::getTime()always corresponds to UTC(virtually the same thing as GMT in this context). To quote the class doc:

不,从返回的值Date::getTime()始终对应于UTC(在这种情况下与 GMT 几乎相同)。引用类文档:

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

返回自 1970 年 1 月 1 日格林威治标准时间 00:00:00 以来由此 Date 对象表示的毫秒数。

So your Question is nonsensical in that a Dateis already in UTC. No need to “get the value back which corresponds to the original UTC time”,

所以你的问题是荒谬的,因为 aDate已经在 UTC 中。无需“取回原始UTC时间对应的值”,

You may be confusing the behavior of getTimewith that of the toStringmethod. The toStringmethod annoyingly and confusingly applies the current default time zone in the process of generating the String. So the string output appears with a time zone while in fact there is no time zone to be set or gotten from the Dateitself. (There actually is a zone deep within the Datebut that is irrelevant to this discussion here. This class is a confusing mess!)

您可能会将 的行为getTimetoString方法的行为混淆。该toString方法在生成字符串的过程中令人讨厌且令人困惑地应用当前默认时区。因此,字符串输出显示时带有时区,而实际上没有要设置或从其Date本身获取时区。(实际上在里面有一个区域,Date但这与这里的讨论无关。这个类是一个混乱的混乱!)

java.time

时间

The modern way to do this is using java.time classes.

现代方法是使用 java.time 类。

Table of date-time types in Java, both modern and legacy

Java 中的日期时间类型表,现代和传统

Instant

Instant

The Instantclass represents a moment on the timeline in UTCwith a resolution of nanoseconds(up to nine (9) digits of a decimal fraction).

Instant级表示时间轴上的时刻UTC,分辨率为纳秒(最多小数的9个位数)。

Get the current moment.

获取当前时刻。

Instant instant = Instant.now();

You can convert a Dateto its modern replacement by calling one of the new conversion methods added to the old date-time classes. Just call toInstant, quite easy.

您可以Date通过调用添加到旧日期时间类的新转换方法之一将 a 转换为其现代替代品。打个电话toInstant,很简单。

Instant instant = myJavaUtilDate.toInstant();  

I do not recommend at all using a count-from-epoch number as a way of tracking time. Stick with the java.time objects instead. When outside Java, serialize to text use the ISO 8601formats.

我根本不建议使用从纪元计数作为跟踪时间的方式。坚持使用 java.time 对象。在 Java 之外,序列化为文本使用ISO 8601格式。

But if you must, you can extract a count of milliseconds since epoch of 1970-01-01T00:00:00Z. Note that this may involve data loss! An Instanthas a finer resolution of nanoseconds. So going to milliseconds may lop off a fraction of the fraction of a second.

但如果必须,您可以提取自 1970-01-01T00:00:00Z 纪元以来的毫秒数。请注意,这可能会导致数据丢失!AnInstant具有更精细的纳秒分辨率。因此,进入毫秒可能会减少几分之一秒的时间。

long millisecondsSinceEpoch = instant.toEpochMilli();  // Caution: Possible data-loss in going from nanoseconds to milliseconds.

Going the other direction, from a count to an Instant.

走向另一个方向,从计数到Instant

Instant instant = Instant.ofEpochMilli( millisecondsSinceEpoch ) ;


About java.time

关于 java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多

回答by Anupam Mahapatra

    LocalDateTime now = LocalDateTime.now(Clock.systemUTC());
    Instant instant = now.atZone(ZoneId.systemDefault()).toInstant();
    Date formattedDate = Date.from(instant);

    return formattedDate;

回答by Amol Dixit

Most of the Date class functions are deprecated as they are now shifted in Calendar class.

大多数 Date 类函数已被弃用,因为它们现在已在 Calendar 类中移动。

Here is code to get UTC time from Calendar.

这是从日历获取 UTC 时间的代码。

Date date = new Date(timeStamp);
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.setTime(date);

Here is the sample code to get the year, month, etc.

这是获取年、月等的示例代码。

System.out.println(calendar.get(Calendar.YEAR));
System.out.println(calendar.get(Calendar.MONTH));

Calendar also has support for many other useful information like, TIME, DAY_OF_MONTH, etc. Here the documentationlisting all of them Please note that the month are 0 based. January is 0th month.

日历还支持许多其他有用的信息,例如 TIME、DAY_OF_MONTH 等。此处列出所有这些信息的文档请注意,月份是从 0 开始的。一月是第 0 个月。