Java 8 LocalDateTime.now()仅提供毫秒精度 [英] Java 8 LocalDateTime.now() only giving precision of milliseconds

查看:179
本文介绍了Java 8 LocalDateTime.now()仅提供毫秒精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java 8中能否获得微秒? Java 8 LocalDateTime 类具有 .getNano()方法,该方法旨在返回 nanoseconds ,但在Linux(Ubuntu)和OS X(10.11.5)上,它仅返回毫秒(当我运行它时,它返回 301000000 等于 301毫秒),我真的需要能够获得 microseconds


我知道有可能获得(因此得到微秒从它)在我的计算机上作为javascript方法 process.hrtime()返回一个精确值。


在任何人之前开始一个精确与精确的论据,我知道线程之间的纳秒是完全不可靠的,不应用于比较。


编辑


为清楚起见, LocalDateTime 类是Java 8 java.time 类集中的一部分。


更新


所以我意识到Javascript是s process.hrtime 类似于Java的 System.nanoTime(),实际上与挂钟无关,它是时间,因为这两种语言之间存在一些不同的任意值。


新问题:是否可以通过这些值解析时钟时间?就是如果我得到 System.currentTimeMillis() System.nanoTime(),并将其与另一组值进行比较我可以获取第二组值的实际时间吗?


我的问题是我需要同时使用Java和Javascript进行日志记录,并且它们在两者之间都必须具有一致的微秒字段

解决方案

tl; dr




在Java 8中有可能获得微秒吗?


否。使用Java 9或更高版本。

  Instant.now()//在Java 9和更高版本中返回以微秒为单位的值,但是在Java 8中限制为毫秒。

这是指Oracle& Java 8/9的OpenJDK实现。其他可能会有所不同。



Java 9和更高版本



Java 9具有



ISO 8601



在ISO 8601中,小数点后的秒可以是任意位数。因此,您真的不应该在乎记录的事件是以毫秒,微秒还是纳秒为单位记录的。

  Instant Instant = Instant。 parse( 2018-03-09T21:03:33.123456789Z); 
Instant Instant = Instant.parse( 2018-03-09T21:03:33.123456Z);
Instant Instant = Instant.parse( 2018-03-09T21:03:33.123Z);



截断



如果您确实认为您需要统一的解决方案,则可以截断即时

 即时即时= Instant.now()。truncatedTo(ChronoUnit.MILLIS); //剥离任何微秒或纳秒。 



不用担心分辨率




我的问题是我需要同时使用Java和Javascript进行日志记录,并且它们之间都必须具有一致的微秒字段。


首先,我怀疑您是否真的需要关心这一点。如果您使用标准ISO 8601格式以及Java中的 Instant 类,则可以成功地序列化并重新水化毫秒,微米或纳米。



ISO 8601格式的字符串将方便地按时间顺序按字母顺序排列,即使小数秒分辨率有所不同。



第二,如果由于某种原因试图将实际时刻跟踪到微秒,您可能会感到失望。截至2018年,常规计算机时钟在微秒范围内并不可靠。






关于 java.time



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



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



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



您可以直接与数据库交换 java.time 对象。使用符合 JDBC驱动程序。 jeps / 170 rel = noreferrer> JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql。* 类。



在哪里获取java.time类?





ThreeTen-Extra 项目使用其他类扩展了java.time。该项目是将来可能向java.time添加内容的试验场。您可能会在这里找到一些有用的类,例如 时间间隔 YearWeek YearQuarter 更多


Is it possible to get microseconds in Java 8? The Java 8 LocalDateTime class has a .getNano() method which is meant to return nanoseconds, but on both Linux(Ubuntu) and OS X (10.11.5) it only returns milliseconds (when I ran it it returned 301000000 which equals 301 milliseconds) and I really need to be able to get microseconds.

I know that it is possible to get nanoseconds (and therefore get microseconds from it) on my computer as the javascript method process.hrtime() returns a precise value.

Before anyone starts a precise vs. accurate argument I know that nanoseconds is completely unreliable between threads and shouldn't be used for comparison.

Edit:

To be clear the LocalDateTime class is part of the Java 8 java.time set of classes.

Update:

So I realised that Javascript's process.hrtime is like Java's System.nanoTime() and isn't actually related to the wall clock, it's time since some arbitrary value which are different between the two languages.

New question: Is there a way that I can parse clock time from these values? Ie. If I get System.currentTimeMillis() and System.nanoTime(), and compare that to another set of those values could I get the actual time of the second set of values?

My problem is that I need to do logging using both Java and Javascript and they need to have a consistent microsecond field across both of them.

解决方案

tl;dr

Is it possible to get microseconds in Java 8?

No. Use Java 9 or later.

Instant.now()  // Returns a value in microseconds in Java 9 and later, but is restricted to mere milliseconds in Java 8.

This refers to the Oracle & OpenJDK implementations of Java 8/9. Others may vary.

Java 9 and later

Java 9 has a fresh implementation of java.time.Clock capable of capturing the current moment in resolution finer than milliseconds (three digits of decimal fraction).

The actual resolution depends on the limits of your host computer hardware clock. On macOS Sierra with Oracle Java 9.0.4, I am getting current moment with microseconds (six digits of decimal fraction).

Instant.now().toString()

2018-03-09T21:03:33.831515Z

Java 8

The java.time classes were new in Java 8. These classes are defined to carry nanoseconds (nine digits of decimal fraction). But capturing the current moment was limited to only milliseconds in Java 8, and enhanced in Java 9 to capture the current moment in finer microseconds.

2018-03-09T21:03:33.831Z

Other issues

System.currentTimeMillis()

If I get System.currentTimeMillis() and System.nanoTime()

No need to use System.currentTimeMillis() ever again. Instead use java.time.Instant for a moment in UTC with a resolution as fine as nanoseconds.

If you really need a count of milliseconds from the epoch reference of 1970-01-01T00:00Z, ask the Instant object. Be aware of data loss, as you would be ignoring any microseconds or nanoseconds present in the Instant.

long millisSinceEpoch = instant.now().toEpochMilli() ;

Is there a way that I can parse clock time from these values?

Yes, you can convert a count of milliseconds since epoch of 1970-01-01T00:00Z to a Instant.

Instant instant = Instant.ofEpochMilli( millisSinceEpoch ) ;

System.nanoTime()

As for System.nanoTime(), that is intended for tracking elapsed time, such as benchmarking your code’ performance. Calling System.nanoTime() does not tell you anything about the current date-time.

This value is a count of nanoseconds since some undocumented origin point in time. In practice, I have seen the number appear to track time since the JVM launched, but this behavior is not documented and so you should not rely upon it.

LocalDateTime is not a moment

My problem is that I need to do logging using both Java and Javascript and they need to have a consistent microsecond field across both of them.

Firstly, for logging you should not be using LocalDateTime class. That class purposely lacks any concept of time zone or offset-from-UTC. As such, a LocalDateTime does not represent a moment, is not a point on the timeline. A LocalDateTime is an idea about potential moments along a range of about 26-27 hours. Use LocalDateTime only if the zone/offset is unknown (not a good situation), or if this represents something like "Christmas Day starts on first moment of Decemeber 25, 2018", where Christmas starts at different moments for different regions around the globe, starting first in the far East (Pacific), and moving westward midnight after successive midnight.

For logging you should be using UTC. In Java, that would be the Instant class, always in UTC by definition. Just call Instant.now().

When serializing to text such as for logging, always use the standard ISO 8601 formats. The java.time classes use these standard formats by default when parsing/generating strings. You saw examples above in this Answer.

See another Question, What's the difference between Instant and LocalDateTime?.

ISO 8601

In ISO 8601, the decimal fraction of a second can have any number of digits. So you really should not care about whether the logged event was recorded in milliseconds, microseconds, or nanoseconds.

Instant instant = Instant.parse( "2018-03-09T21:03:33.123456789Z" ) ;
Instant instant = Instant.parse( "2018-03-09T21:03:33.123456Z" ) ;
Instant instant = Instant.parse( "2018-03-09T21:03:33.123Z" ) ;

Truncate

If you really believe you need uniform resolution, you can truncate a Instant.

Instant instant = Instant.now().truncatedTo( ChronoUnit.MILLIS ) ; // Strip away any microseconds or nanoseconds.

Don't worry about resolution

My problem is that I need to do logging using both Java and Javascript and they need to have a consistent microsecond field across both of them.

Firstly, I doubt you really need to care about this. If you use standard ISO 8601 format, and the Instant class in Java, you can serialize and re-hydrate a moment successfully in millis, micros, or nanos.

And the ISO 8601 formatted strings will conveniently alphabetize chronologically even if the fractional second resolution varies.

Secondly, if you are trying to track actual moments to microseconds for some reason, you are likely to be disappointed. As of 2018, conventional computer clocks are not reliable in the microsecond range.


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.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

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.

这篇关于Java 8 LocalDateTime.now()仅提供毫秒精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆