我查看了下面的页面,2009年在Java中没有方法以微秒为单位精确获取当前时间。
Current time in microseconds in java
最好的是System.currentTimeMillis(),它以毫秒为单位提供当前时间,而System.nanoTime()以纳秒为单位提供当前时间戳,但此时间戳不能用于高精度地转换为当前时间。
我想知道Java在6年后有什么新的更新吗?谢谢。
Edit1.System.nanoTime()用于估计持续时间,但不提供当前时间。
编辑2.在Java 8中有解决方案很好。在Java 7中有没有其他方法可以做到这一点?谢谢!
发布于 2015-11-02 07:28:29
Java8 java.time
包提供了您需要的东西。
尝试:
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
要仅将nanos作为字符串获取,请使用以下格式的nnnnnnnnn
:
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.nnnnnnnnn"));
发布于 2015-11-02 07:33:34
从新的Java8 java.time获取当前时间的另一种方法是Clock类
Clock.systemUTC().millis()
给出当前时间,单位为毫秒(从纪元开始的长值毫秒)或
Clock.systemUTC().instant()
根据the official Oracle Java tutorial返回Instant类的实例“表示时间轴上纳秒的开始”。本教程介绍了如何使用新类,如何转换为本地或UTC或分区日期时间等
https://stackoverflow.com/questions/33472569
复制