来自 ZonedDateTime UTC 实例的 Java 日期和时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43259722/
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
Java Date and Timestamp from instance of ZonedDateTime UTC
提问by DevelopingDeveloper
I have a java application in which I would like the time in UTC. Currently, the code uses a mix of java.util.Date
and java.sql.Timestamp
. To get the time in UTC, the programmer before me used:
我有一个 Java 应用程序,我希望在其中使用 UTC 时间。目前,该代码混合使用java.util.Date
和java.sql.Timestamp
。为了获得UTC时间,我之前的程序员使用:
For Date:
日期:
Date.from(ZonedDateTime.now(ZoneOffset.UTC)).toInstant();
For Timestamp:
对于时间戳:
Timestamp.from(ZonedDateTime.now(ZoneOffset.UTC).toInstant());
However I have run multiple tests myself with this code and both of these lines return the current date/time(in my current timezone). From everything I have read it appearsthat Date/Timestamp does not have a zoneOffset value, but I cannot find a concrete statement of this.
但是,我自己使用此代码运行了多个测试,这两行都返回当前日期/时间(在我当前的时区)。从我读过的所有内容来看,日期/时间戳似乎没有 zoneOffset 值,但我找不到具体的说明。
Is there anyway to keep the timeZone (UTC) within the Date or Timestamp objects, or do I need to do some refactoring and use the actual ZonedDateTime object throughout my application? Also will this ZonedDateTime object be compatible with the current Timestamp object for sql?
无论如何要在 Date 或 Timestamp 对象中保留 timeZone (UTC),或者我是否需要进行一些重构并在整个应用程序中使用实际的 ZonedDateTime 对象?这个 ZonedDateTime 对象是否与当前的 sql 时间戳对象兼容?
Example:
例子:
public static void main (String args[])
{
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneOffset.UTC);
Timestamp timestamp = Timestamp.from(ZonedDateTime.now(ZoneOffset.UTC).toInstant());
Date date = Date.from(ZonedDateTime.now(ZoneOffset.UTC).toInstant());
System.out.println("ZonedDateTime: " + zonedDateTime);
System.out.println("Timestamp: " + timestamp);
System.out.println("Date: " + date);
}
Output:
输出:
ZonedDateTime: 2017-04-06T15:46:33.099Z
Timestamp: 2017-04-06 10:46:33.109
Date: Thu Apr 06 10:46:33 CDT 2017
采纳答案by Basil Bourque
tl;dr
tl;博士
Instant.now() // Capture the current moment in UTC with a resolution up to nanoseconds.
Use only java.timeclasses. Avoid the troublesome old legacy date-time classes added before Java 8.
仅使用java.time类。避免在 Java 8 之前添加的麻烦的旧的遗留日期时间类。
Using java.time
使用 java.time
The programmer before you was making use of the new modern java.time classes that now supplant the notoriously troublesome old legacy date-time classes such as Date
, Calendar
, Timestamp
.
您之前的程序员正在使用新的现代 java.time 类,这些类现在取代了臭名昭著的旧的遗留日期时间类,例如Date
, Calendar
, Timestamp
。
Instant
Instant
The Instant
class represents a moment on the timeline in UTCwith a resolution of nanoseconds(up to nine (9) digits of a decimal fraction). To get the current moment in UTC is utterly simple: Instant.now
.
该Instant
级表示时间轴上的时刻UTC,分辨率为纳秒(最多小数的9个位数)。为了在UTC获得当前时刻是简单得不能再简单:Instant.now
。
Instant instant = Instant.now();
Converting
转换
You should stick to the java.time classes, and avoid the legacy classes. But if absolutely necessary such as interfacing with old code not yet updated for java.time, you may convert to/from java.time. Look to new methods on old classes. The legacy class java.util.Date
equivalent is Instant
.
您应该坚持使用 java.time 类,并避免使用遗留类。但如果绝对必要,例如与尚未为 java.time 更新的旧代码接口,您可以转换为/从 java.time。寻找旧类的新方法。遗留类的java.util.Date
等效项是Instant
.
java.util.Date d = java.util.Date.from( myInstant); // To legacy from modern.
Instant instant = myJavaUtilDate.toInstant(); // To modern from legacy.
JDBC
JDBC
Avoid the legacy date-time classes. Use java.time classes instead.
避免使用旧的日期时间类。改用 java.time 类。
Your JDBC 4.2compliant drivermay be able to directly address java.time types by calling PreparedStatement::setObject
and ResultSet::getObject
.
您的JDBC 4.2兼容驱动程序可能能够通过调用PreparedStatement::setObject
和直接处理 java.time 类型ResultSet::getObject
。
myPreparedStatement.setObject( … , instant ) ;
… and …
… 和 …
Instant instant = myResultSet.getObject( … , Instant.class ) ;
If not, fall back to using the java.sql types, but as briefly as possible. Use new conversion methods added to the old classes.
如果没有,请回退到使用 java.sql 类型,但要尽可能简短。使用添加到旧类的新转换方法。
myPreparedStatement.setTimestamp( … , java.sql.Timestamp.from( instant ) ) ;
… and …
… 和 …
Instant instant = myResultSet.getTimestamp( … ).toInstant() ;
No need for ZonedDateTime
不需要 ZonedDateTime
Notice that we had no need for your mentioned ZonedDateTime
as you said you were only interested in UTC. The Instant
objects are always in UTC. That means that original code you quoted:
请注意,我们不需要您提及,ZonedDateTime
因为您说您只对 UTC 感兴趣。的Instant
对象都可以在UTC。这意味着您引用的原始代码:
Date.from(ZonedDateTime.now(ZoneOffset.UTC)).toInstant();
…could have simply been shortened to:
……可以简单地缩短为:
Date.from( Instant.now() ) ;
Note that java.util.Date
is always in UTC as well. However, its toString
unfortunately applies the JVM' current default time zone implicitly while generating the String. This anti-feature creates no end of confusion as you can see by searching on Stack Overflow.
请注意,它java.util.Date
也始终采用 UTC。然而,toString
不幸的是,它在生成字符串时隐式地应用了 JVM 的当前默认时区。正如您可以通过在 Stack Overflow 上搜索看到的那样,此反功能会造成无休止的混乱。
If you want to see your Instant
object's UTC value through the lens of a region's wall-clock time, assign a time zone ZoneId
to get a ZoneDateTime
.
如果您想Instant
通过一个区域的挂钟时间的镜头查看对象的 UTC 值,请指定一个时区ZoneId
以获取ZoneDateTime
.
Specify a proper time zone namein the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as CDT
or EST
or IST
as they are nottrue time zones, not standardized, and not even unique(!).
以、、 或等格式指定正确的时区名称。切勿使用 3-4 个字母的缩写,例如or或,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/region
America/Montreal
Africa/Casablanca
Pacific/Auckland
CDT
EST
IST
ZoneId z = ZoneId.of( "America/Chicago" );
ZonedDateTime zdt = instant.atZone( z );
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, Java SE 10, Java SE 11, and later - 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.timeclasses.
- For earlier Android (<26), the ThreeTenABPproject adapts ThreeTen-Backport(mentioned above). See How to use ThreeTenABP….
- Java SE 8、Java SE 9、Java SE 10、Java SE 11及更高版本 - 标准 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 Darshan Mehta
In Java, Date
represents a point in time. It's not related to timestamp. When you call toString()
method of a Date
object, it converts that time to Platform's default Timestamp, e.g. Following will print date/time in UTC (as it sets default timezone to UTC):
在 Java 中,Date
代表一个时间点。它与时间戳无关。当您调用对象的toString()
方法时Date
,它会将该时间转换为平台的默认时间戳,例如,以下将以 UTC 打印日期/时间(因为它将默认时区设置为 UTC):
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneOffset.UTC);
Timestamp timestamp = Timestamp.from(ZonedDateTime.now(ZoneOffset.UTC).toInstant());
Date date = Date.from(ZonedDateTime.now(ZoneOffset.UTC).toInstant());
System.out.println("ZonedDateTime: " + zonedDateTime);
System.out.println("Timestamp: " + timestamp);
System.out.println("Date: " + date);