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

发布于 2024-08-24 03:19:57 字数 120 浏览 9 评论 0原文

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

谢谢

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?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

无畏 2024-08-31 03:19:57

tl;dr

Instant.now()

…和…

Instant.ofEpochMilli( n ) 

…和…

instant.toEpochMilli()

日期 始终采用 UTC

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

否,从 Date::getTime() 始终对应于 UTC (在这种情况下,实际上与 GMT 相同)。引用课程文档:

返回此 Date 对象表示的自 1970 年 1 月 1 日 00:00:00 GMT 以来的毫秒数。

因此,您的问题是无意义的,因为 Date 已经采用 UTC 格式。无需“获取与原始 UTC 时间相对应的值”,

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

java.time

执行此操作的现代方法是使用 java.time 类。

表格Java 中的日期时间类型(现代和传统)

Instant

Instant 类表示 UTC,分辨率为 纳秒 (最多九 (9) 位小数)。

获取当前时刻。

Instant instant = Instant.now();

您可以通过调用添加到旧日期时间类的新转换方法之一,将 Date 转换为其现代替代品。只需调用toInstant,非常简单。

Instant instant = myJavaUtilDate.toInstant();  

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

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

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

走向另一个方向,从计数到即时

Instant instant = Instant.ofEpochMilli( millisecondsSinceEpoch ) ;

关于 java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如java.util.Date, 日历, & ; SimpleDateFormat

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

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

从哪里获取 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如 间隔YearWeek<代码>YearQuarter,以及更多

tl;dr

Instant.now()

…and…

Instant.ofEpochMilli( n ) 

…and…

instant.toEpochMilli()

Date is always in 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).

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:

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

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

You may be confusing the behavior of getTime with that of the toString method. The toString method 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 Date itself. (There actually is a zone deep within the Date but that is irrelevant to this discussion here. This class is a confusing mess!)

java.time

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

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

Instant

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Get the current moment.

Instant instant = Instant.now();

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

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 8601 formats.

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 Instant has a finer resolution of nanoseconds. So going to milliseconds may lop off a fraction of the fraction of a second.

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.ofEpochMilli( millisecondsSinceEpoch ) ;

About java.time

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

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

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

Where to obtain the java.time classes?

The ThreeTen-Extra project 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.

灵芸 2024-08-31 03:19:57

DateFormat 类具有 设置首选时区的方法,并且有一个时区类具有 UTC 时间设置

所以,举例来说,

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

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

So, for example,

SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC"));
Date yourUtcDate = sdf.parse(yourOriginalDate);
夏末的微笑 2024-08-31 03:19:57

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

java.util.Date has 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 DateFormat to display a Date in a different timezone (such as UTC), or change the JVM's default timezone.

getTime() 返回“自 1970 年 1 月 1 日 00:00:00 GMT 以来的毫秒数”,仅此而已(显然,您必须正确创建它)。您可以根据需要设置其格式,例如从 GregorianCalendar(TimeZone) 构造函数开始。

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.

拥抱我好吗 2024-08-31 03:19:57

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

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

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

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

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

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

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

Here is code to get UTC time from Calendar.

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 documentation listing all of them Please note that the month are 0 based. January is 0th month.

可爱咩 2024-08-31 03:19:57
    LocalDateTime now = LocalDateTime.now(Clock.systemUTC());
    Instant instant = now.atZone(ZoneId.systemDefault()).toInstant();
    Date formattedDate = Date.from(instant);

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

    return formattedDate;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文