15

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

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.

May I know if there is any new update in this for Java after 6 years? Thanks.

Edit 1. System.nanoTime() is useful for estimating duration, but not giving current time.

Edit 2. It is good to have solutions in Java 8. Is there any other way to do it in Java 7? Thanks!

Community
  • 1
  • 1
ysrhung
  • 554
  • 2
  • 6
  • 11
  • Nanoseconds are more precise than microseconds. Also a solution was provided in your [post](http://stackoverflow.com/a/33129599/4105457) – Flown Nov 02 '15 at 07:26
  • Possible duplicate of [System.currentTimeMillis vs System.nanoTime](http://stackoverflow.com/questions/351565/system-currenttimemillis-vs-system-nanotime) – Andrei Sfat Nov 02 '15 at 07:27
  • 1
    Of course the precision of the timing logic is fully operating system and hardware dependent, it is not actually Java producing the numbers. – Gimby Nov 02 '15 at 08:41
  • @BasilBourque Thanks, I have deleted my comment. I wrote that comment long back without fully understand that the OP is looking for accuracy. – Mitesh Pathak Aug 29 '19 at 17:11

3 Answers3

15

tl;dr

Instant.now()

2018-03-09T21:03:33.831515Z

Using Java 9 and later, you can likely capture the current moment with microseconds resolution.

Example seen above is Oracle Java 9.0.4 for macOS Sierra. Note the 6 digits of fractional second, meaning microseconds.


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 9

The OpenJDK implementation of Java 9 has a fresh implementation of Clock with up to nanosecond resolution. Actual values depend on the limits of the underlying hardware clock of any particular computer.

For more info see the Question, Why does the new Java 8 Date Time API not have nanosecond precision?.

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 8

Java 8 implements the Clock interface with only millisecond resolution (3 digits of a fractional second). So while the java.time classes are capable of carrying nanoseconds, it is not able to capture the current time with nanoseconds.

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.

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.time objects with your database.

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, Postgres provides microsecond resolution (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.

enter image description here


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.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

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. Hibernate 5 & JPA 2.2 support java.time.

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
6

The Java 8 java.time package has what you need.

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:

LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.nnnnnnnnn"));  
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • Parse it to a Date object and further if you need more formatting use `SimpleDateFormatter` – Jude Niroshan Nov 02 '15 at 07:42
  • @JudeNiroshan FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html), and `java.text.SimpleTextFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jun 20 '17 at 04:47
2

Another way to get current time from the new Java 8 java.time is the Clock class

Clock.systemUTC().millis()

gives current time in millis (long value millis since epoch) or

Clock.systemUTC().instant()

returns an instance of Instant class "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

Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47