如何在 Java 8 中获取 UTC+0 日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26142864/
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
How to get UTC+0 date in Java 8?
提问by Mark
I have problems with Date class in Java. Date class returns local machine date but i need UTC-0.
我对 Java 中的 Date 类有问题。日期类返回本地机器日期,但我需要 UTC-0。
I have googled and found great solution for JavaScript but for Java nothing useful.
我在谷歌上搜索并找到了很好的 JavaScript 解决方案,但对于 Java 没有任何用处。
How to get UTC+0 date in Java 8?
如何在 Java 8 中获取 UTC+0 日期?
采纳答案by assylias
With Java 8 you can write:
使用 Java 8,您可以编写:
OffsetDateTime utc = OffsetDateTime.now(ZoneOffset.UTC);
To answer your comment, you can then convert it to a Date (unless you depend on legacy code I don't see any reason why) or to millis since the epochs:
要回答您的评论,您可以将其转换为日期(除非您依赖于遗留代码,我看不出任何原因)或自纪元以来的毫秒数:
Date date = Date.from(utc.toInstant());
long epochMillis = utc.toEpochSecond() * 1000;
回答by rolfl
In Java8 you use the new Time API, and convert an Instantin to a ZonedDateTimeUsing the UTC TimeZone
在 Java8 中,您使用新的 Time API,并使用UTC TimeZone将Instant转换为ZonedDateTime
回答by Abel Terefe
In java8, I would use the Instant
class which is already in UTCand is convenient to work with.
在 java8 中,我将使用Instant
已经在UTC 中并且易于使用的类。
import java.time.Instant;
Instant ins = Instant.now();
long ts = ins.toEpochMilli();
Instant ins2 = Instant.ofEpochMilli(ts)
Alternatively, you can use the following:
或者,您可以使用以下方法:
import java.time.*;
Instant ins = Instant.now();
OffsetDateTime odt = ins.atOffset(ZoneOffset.UTC);
ZonedDateTime zdt = ins.atZone(ZoneId.of("UTC"));
Back to Instant
回到 Instant
Instant ins4 = Instant.from(odt);
回答by Basil Bourque
tl;dr
tl;博士
Instant.now()
java.time
时间
The troublesome old date-time classes bundled with the earliest versions of Java have been supplanted by the java.timeclasses built into Java 8 and later. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backportand further adapted to Android in ThreeTenABP.
与最早版本的 Java 捆绑在一起的麻烦的旧日期时间类已被Java 8 及更高版本中内置的java.time类所取代。请参阅Oracle 教程。许多功能已被后移植到Java 6和7在ThreeTen-反向移植和在进一步适于到Android ThreeTenABP。
Instant
Instant
An Instant
represents a moment on the timeline in UTCwith a resolution of up to nanoseconds.
AnInstant
代表UTC时间线上的一个时刻,分辨率高达纳秒。
Instant instant = Instant.now();
The toString
method generates a String object with text representing the date-time value using one of the standard ISO 8601formats.
该toString
方法使用标准ISO 8601格式之一生成一个字符串对象,其中包含表示日期时间值的文本。
String output = instant.toString();
2016-06-27T19:15:25.864Z
2016-06-27T19:15:25.864Z
The Instant
class is a basic building-block class in java.time. This should be your go-to class when handling date-time as generally the best practice is to track, store, and exchange date-time values in UTC.
该Instant
班是java.time一个基本构建块类。这应该是您处理日期时间时的首选课程,因为通常最佳实践是以 UTC 跟踪、存储和交换日期时间值。
OffsetDateTime
OffsetDateTime
But Instant
has limitations such as no formatting options for generating strings in alternate formats. For more flexibility, convert from Instant
to OffsetDateTime
. Specify an offset-from-UTC. In java.time that means a ZoneOffset
object. Here we want to stick with UTC (+00) so we can use the convenient constant ZoneOffset.UTC
.
但是Instant
有一些限制,例如没有用于以替代格式生成字符串的格式选项。为了获得更大的灵活性,请从 转换Instant
为OffsetDateTime
。指定一个offset-from-UTC。在 java.time 中,这意味着一个ZoneOffset
对象。在这里,我们想坚持使用 UTC (+00),这样我们就可以使用方便的常量ZoneOffset.UTC
。
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
2016-06-27T19:15:25.864Z
2016-06-27T19:15:25.864Z
Or skip the Instant
class.
或者跳过Instant
课程。
OffsetDateTime.now( ZoneOffset.UTC )
Now with an OffsetDateTime
object in hand, you can use DateTimeFormatter
to create String objects with text in alternate formats. Search Stack Overflow for many examples of using DateTimeFormatter
.
现在有了一个OffsetDateTime
对象,您可以使用DateTimeFormatter
替代格式的文本创建 String 对象。在 Stack Overflow 上搜索许多使用DateTimeFormatter
.
ZonedDateTime
ZonedDateTime
When you want to display wall-clock timefor some particular time zone, apply a ZoneId
to get a ZonedDateTime
.
如果您想显示某个特定时区的挂钟时间,请应用 aZoneId
以获取ZonedDateTime
.
In this example we apply Montréal time zone. In the summer, under Daylight Saving Time (DST)nonsense, the zone has an offset of -04:00
. So note how the time-of-day is four hours earlier in the output, 15
instead of 19
hours. Instant
and the ZonedDateTime
both represent the very same simultaneous moment, just viewed through two different lenses.
在本例中,我们应用蒙特利尔时区。在夏季,根据夏令时 (DST)废话,该区域的偏移量为-04:00
. 所以请注意输出中的时间如何提前四个小时,15
而不是19
几个小时。Instant
并且ZonedDateTime
两者都代表相同的同时时刻,只是通过两个不同的镜头观看。
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
2016-06-27T15:15:25.864-04:00[America/Montreal]
2016-06-27T15:15:25.864-04:00[美国/蒙特利尔]
Converting
转换
While you should avoid the old date-time classes, if you must you can convert using new methods added to the old classes. Here we use java.util.Date.from( Instant )
and java.util.Date::toInstant
.
虽然您应该避免使用旧的日期时间类,但如果必须,您可以使用添加到旧类中的新方法进行转换。这里我们使用java.util.Date.from( Instant )
和java.util.Date::toInstant
。
java.util.Date utilDate = java.util.Date.from( instant );
And going the other direction.
并走向另一个方向。
Instant instant= utilDate.toInstant();
Similarly, look for new methods added to GregorianCalendar
(subclass of Calendar
) to convert to and from java.time.ZonedDateTime
.
类似地,寻找添加到GregorianCalendar
( 的子类Calendar
)的新方法以在 和 之间进行转换java.time.ZonedDateTime
。
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。
You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*
classes.
您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8, Java SE 9, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABPproject adapts ThreeTen-Backport(mentioned above). See How to use ThreeTenABP….
- Java SE 8、Java SE 9及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- java.time 类的更高版本的 Android 捆绑实现。
- 对于早期的 Android(<26),ThreeTenABP项目采用了ThreeTen-Backport(上面提到过)。请参阅如何使用ThreeTenABP ...。
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 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。
回答by Abhijeet Ashok Muneshwar
1 line solution in Java 8:
Java 8 中的 1 行解决方案:
public Date getCurrentUtcTime() {
return Date.from(Instant.now());
}