Java:如何以 ISO 8601 SECOND 格式获取当前日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13545735/
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: How to get current date in ISO 8601 SECOND format
提问by marcolopes
I need to get the current date in ISO 8601with SS millisecondsand HH:MM timezone
我需要使用SS 毫秒和HH:MM 时区获取ISO 8601 中的当前日期
Complete date plus hours, minutes, seconds and a decimal fraction of a second: YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
完整日期加上小时、分钟、秒和小数秒:YYYY-MM-DDThh:mm:ss.sTZD(例如 1997-07-16T19:20:30. 45+01:00)
see: http://www.w3.org/TR/NOTE-datetime
见:http: //www.w3.org/TR/NOTE-datetime
i tried different approaches, but i cannot get the correct milliseconds & timezone digits:
我尝试了不同的方法,但我无法获得正确的毫秒数和时区数字:
DateFormat df=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSZZ");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
df.format(new Date());
JAVA result:2012-11-24T21:19:27.758+0000
JAVA 结果:2012-11-24T21:19:27。758+0000
Apache result:2012-11-24T21:19:27.758+00:00(Apache Commons FastDateFormat)
Apache 结果:2012-11-24T21:19:27。758+00:00(Apache Commons FastDateFormat)
回答by Tomasz Nurkiewicz
Actually there is a class in JDK that handles parsing and formatting ISO8601:
实际上JDK中有一个类可以处理解析和格式化ISO8601:
import javax.xml.bind.DatatypeConverter;
DatatypeConverter.printDateTime(new GregorianCalendar())
//2012-11-24T22:42:03.142+01:00
回答by Basil Bourque
tl;dr
tl;博士
Current moment, UTC
当前时刻,UTC
Use java.time.Instant
to capture the current moment in a resolution as fine as nanoseconds.
用于java.time.Instant
以纳秒级的分辨率捕捉当前时刻。
Instant.now() // Capture the current moment in UTC, with a resolution as fine as nanoseconds. Typically captured in microseconds in Java 9 and later, milliseconds in Java 8.
.toString() // Generate a `String` representing the value of this `Instant` in standard ISO 8601 format.
2018-01-23T12:34:56.123456Z
2018-01-23T12:34:56.123456Z
The Z
on the end:
在Z
上月底:
- means UTC,
- is equivalent to
+00:00
offset, - is pronounced “Zulu”, and
- is defined by the ISO 8601standard as well as other arenas such as military.
Current moment, specific offset
当前时刻,特定偏移量
If for some unusual reason you must adjust into a specific offset-from-UTC, use OffsetDateTime
, passing a ZoneOffset
.
如果由于某些不寻常的原因,您必须调整为特定的偏移距 UTC,请使用OffsetDateTime
,传递一个ZoneOffset
.
OffsetDateTime.now( // Capture the current moment.
ZoneOffset.ofHours( 1 ) // View the current moment adjusted to the wall-clock time of this specific offset-from-UTC. BTW, better to use time zones, generally, than a mere offset-from-UTC.
)
.toString() // Generate a `String` in standard ISO 8601 format.
2018-07-08T21:13:10.723676+01:00
2018-07-08T21:13:10.723676+01:00
Current moment, truncated to millis
当前时刻,截断为毫秒
For milliseconds resolution, truncate. Specify resolution by ChronoUnit
enum.
对于毫秒分辨率,请截断。通过ChronoUnit
枚举指定分辨率。
OffsetDateTime.now(
ZoneOffset.ofHours( 1 )
)
.truncatedTo( // Lop off finer part of the date-time. We want to drop any microseconds or nanoseconds, so truncate to milliseconds. Using the immutable objects pattern, so a separate new `OffsetDateTime` object is generated based on the original object's values.
ChronoUnit.MILLIS // Specify your desired granularity via `ChronoUnit` enum.
)
.toString()
2018-07-08T21:13:10.723+01:00
2018-07-08T21:13:10.723+01:00
java.time
时间
The java.time frameworkbuilt into Java 8 and later uses ISO 8601be default when parsing or generating textual representations of date-time values.
在解析或生成日期时间值的文本表示时,Java 8 及更高版本中内置的java.time 框架默认使用ISO 8601。
An Instant
is a moment on the timeline in UTCwith a resolution of nanoseconds.
AnInstant
是UTC时间线上的一个时刻,分辨率为纳秒。
Instant instant = Instant.now();
The current moment is captured with a resolution of milliseconds in Java 8, and in Java 9 and later, typically a resolution of microseconds depending on capabilities of host hardware clock and OS. If you specifically want milliseconds resolution, truncate any microseconds or nanoseconds.
在 Java 8 中以毫秒的分辨率捕获当前时刻,在 Java 9 及更高版本中,通常是微秒的分辨率,具体取决于主机硬件时钟和操作系统的功能。如果您特别想要毫秒分辨率,请截断任何微秒或纳秒。
Instant instant = Instant.now().truncatedTo( ChronoUnit.MILLIS ) ;
But you want a specific offset-from-UTC. So specify a ZoneOffset
to get a OffsetDateTime
.
但是你想要一个特定的offset-from-UTC。所以指定 aZoneOffset
以获得 a OffsetDateTime
。
ZoneOffset offset = ZoneOffset( "+01:00" );
OffsetDateTime odt = OffsetDateTime.ofInstant( instant , offset );
Again, truncate if you specifically want milliseconds resolution rather than microseconds or nanoseconds.
同样,如果您特别想要毫秒分辨率而不是微秒或纳秒,请截断。
odt = odt.truncatedTo( ChronoUnit.MILLIS ) ; // Replace original `OffsetDateTime` object with new `OffsetDateTime` object based on the original but with any micros/nanos lopped off.
To generate your ISO 8601 string, simply call toString
.
要生成 ISO 8601 字符串,只需调用toString
.
String output = odt.toString();
Dump to console. Note in the output how the hour rolled forward as an adjustment to the +01:00
offset, and that even rolled over midnight so the date changed from the 12th to the 13th.
转储到控制台。请注意输出中的小时如何作为对+01:00
偏移量的调整向前滚动,甚至在午夜滚动,因此日期从 12 日更改为 13 日。
System.out.println ( "instant: " + instant + " | offset: " + offset + " | odt: " + odt );
instant: 2016-04-12T23:12:24.015Z | offset: +01:00 | odt: 2016-04-13T00:12:24.015+01:00
即时:2016-04-12T23:12:24.015Z | 偏移量:+01:00 | 时间:2016-04-13T00:12:24.015+01:00
Zoned
分区
By the way, it is better to use a time zone (if known) than just a mere offset. A time zone a history of the past, present, and future changes in offset used by the people of a particular region.
顺便说一句,最好使用时区(如果已知)而不仅仅是偏移量。时区是特定地区人民过去、现在和未来使用的偏移量变化的历史记录。
In java.time that means applying a ZoneId
to get a ZonedDateTime
.
在 java.time 中,这意味着应用 aZoneId
来获得 a ZonedDateTime
。
ZoneId zoneId = ZoneId.of( "Europe/Paris" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Or skip Instant
, as a shortcut.
或者跳过Instant
,作为快捷方式。
ZonedDateTime zdt = ZonedDateTime.now( zoneId ) ;
Generate a String
representing textually the value of that ZonedDateTime
object. The format used by default is standard ISO 8601 format wisely extended to append the name of the zone in square brackets.
生成一个String
以文本方式表示该ZonedDateTime
对象的值。默认使用的格式是标准 ISO 8601 格式,明智地扩展为在方括号中附加区域名称。
zdt.toString(): 2018-07-08T22:06:58.780923+02:00[Europe/Paris]
zdt.toString(): 2018-07-08T22:06:58.780923+02:00[欧洲/巴黎]
For other formats, use the DateTimeFormatter
class.
对于其他格式,请使用DateTimeFormatter
类。
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, 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.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 API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- 更高版本的 Android 捆绑实现java.time类。
- 对于早期的 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
,和更多。