现在有什么新方法可以在 Java 中以微秒为单位准确地获取当前时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33472569/
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
Any new method to get current time with accuracy in microseconds in Java now?
提问by ysrhung
I checked the below page that there is no method to get current time with accuracy in microsecond in Java in 2009.
Current time in microseconds in java
我检查了下面的页面,没有方法可以在 2009 年的 Java 中以微秒为单位准确地获取当前时间。 java 中的
当前时间以微秒为单位
The best one is System.currentTimeMillis() which gives current time with accuracy in millisecond, while System.nanoTime() gives the current timestamp with accuracy in nanoseconds, but this timestamp could not be used to convert to current time with high accuracy.
最好的方法是 System.currentTimeMillis(),它以毫秒为单位准确给出当前时间,而 System.nanoTime() 以纳秒为单位准确给出当前时间戳,但该时间戳不能用于高精度转换为当前时间。
May I know if there is any new update in this for Java after 6 years? Thanks.
我可以知道 6 年后 Java 是否有任何新的更新?谢谢。
Edit 1. System.nanoTime() is useful for estimating duration, but not giving current time.
编辑 1. System.nanoTime() 可用于估计持续时间,但不提供当前时间。
Edit 2. It is good to have solutions in Java 8. Is there any other way to do it in Java 7? Thanks!
编辑 2. 在 Java 8 中有解决方案很好。在 Java 7 中有没有其他方法可以做到这一点?谢谢!
回答by Basil Bourque
tl;dr
tl;博士
Instant.now()
2018-03-09T21:03:33.831515Z
2018-03-09T21:03:33.831515Z
Using Java 9and later, you can likely capture the current moment with microsecondsresolution.
使用Java 9及更高版本,您可能可以以微秒分辨率捕捉当前时刻。
Example seen above is Oracle Java 9.0.4 for macOS Sierra. Note the 6 digits of fractional second, meaning microseconds.
上面看到的示例是适用于macOS Sierra 的Oracle Java 9.0.4 。注意小数秒的 6 位数字,意思是微秒。
java.time
时间
The java.time framework built into Java 8 and later has classes to represent date-time values with a resolution of nanoseconds, 9 digits of a decimal fraction of a second.
Java 8 及更高版本中内置的 java.time 框架具有表示日期时间值的类,其分辨率为nanoseconds,即 9 位秒的十进制小数。
Java 9
爪哇 9
Java 9 has a fresh implementationof Clock
with up to nanosecond resolution. Actual values depend on the limits of the underlying hardware clock of any particular computer.
Java的9拥有新鲜实施的Clock
高达纳秒级的分辨率。实际值取决于任何特定计算机的底层硬件时钟的限制。
For more info see the Question, Why does the new Java 8 Date Time API not have nanosecond precision?.
有关更多信息,请参阅问题,为什么新的 Java 8 日期时间 API 没有纳秒精度?.
Avoid the older date-time classes. The classes such as java.util.Date/.Calendar bundled with early versions of Java have only millisecond resolution. Same for Joda-Time. Both are supplanted by the java.time classes.
避免使用较旧的日期时间类。与早期 Java 版本捆绑在一起的 java.util.Date/.Calendar 等类只有毫秒分辨率。同为乔达时间。两者都被 java.time 类所取代。
Java 8
爪哇 8
Java 8 implements the Clock
interface with only millisecondresolution (3 digits of a fractional second). So while the java.time classes are capable of carryingnanoseconds, it is not able to capturethe current time with nanoseconds.
Java 8 实现的Clock
接口只有毫秒分辨率(小数秒的 3 位数字)。因此,虽然 java.time 类能够携带纳秒,但它无法用纳秒捕获当前时间。
Native code
本机代码
Perhaps you could write or find an implementation of Clock
that makes a call to a native library in the host OS to get a more accurate time.
也许您可以编写或找到一个实现,Clock
它可以调用主机操作系统中的本机库以获得更准确的时间。
Database
数据库
If you happen to be using a database already, you could ask it for the time. As of JDBC 4.2 and later, you can directly exchange java.timeobjects with your database.
如果您碰巧已经在使用数据库,则可以询问它的时间。从 JDBC 4.2 及更高版本开始,您可以直接与数据库交换java.time对象。
Instant instant = myPreparedStatement.getObject( … , Instant.class ) ;
Prior to JDBC 4.2, you could go through the troublesome legacy java.sql.Timestamp
that carries nanosecond resolution. For example, Postgresprovides microsecondresolution (assuming the host computer clock supports that), 6 digits of a fractional second. You can convert from a java.sql.Timestamp
to an Instant
and ZonedDateTime
using new methods added to the old classes.
在 JDBC 4.2 之前,您可能会遇到java.sql.Timestamp
带有纳秒分辨率的麻烦遗留问题。例如,Postgres提供微秒分辨率(假设主机时钟支持),6 位小数秒。您可以将 a 转换java.sql.Timestamp
为 anInstant
并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-反向移植。
- 安卓
- 更高版本的 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
,和更多。
回答by Bohemian
The Java 8 java.time
package has what you need.
Java 8java.time
包有你需要的东西。
Try:
尝试:
LocalDateTime.now(); // The current timestamp accurate to nanoseconds
LocalDateTime.now().getLong(ChronoField.MICRO_OF_SECOND); // the microseconds part
LocalDateTime.now().getLong(ChronoField.NANO_OF_SECOND); // even finer
LocalDateTime.now().getDayOfMonth(); // main parts of the date have their own methods
LocalDateTime.now().getMonth(); // etc
To just get nanos as a String, use nnnnnnnnn
in the format:
要将 nanos 作为字符串获取,请使用nnnnnnnnn
以下格式:
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.nnnnnnnnn"));
回答by Sharon Ben Asher
Another way to get current time from the new Java 8 java.time is the Clockclass
从新的 Java 8 java.time 获取当前时间的另一种方法是Clock类
Clock.systemUTC().millis()
gives current time in millis (long value millis since epoch) or
以毫秒为单位给出当前时间(自纪元以来的长值毫秒)或
Clock.systemUTC().instant()
returns an instance of Instantclass "which represents the start of a nanosecond on the timeline" according to the official Oracle Java tutorial. The tutorial shows how to work with the new class, convert to local or UTC or zoned date time, etc
根据官方的 Oracle Java 教程,返回Instant类的一个实例“它代表时间轴上一纳秒的开始” 。本教程展示了如何使用新类,转换为本地或 UTC 或分区日期时间等