Search code examples
javasystemtime

Accurate System time


What is the best way to get the most accurate system time (hours minutes and seconds) correct upto milliseconds in java. I have been looking into Clock, Date and Calendar objects. I want to be able to timestamp a packet with the most accurate System time and send it over the network(accurate to Milli or even NanoSeconds if possible).


Solution

  • Java 9

    The java.time framework supports values with up to nanosecond resolution. That means up to nine (9) digits of a decimal fraction of second.

    In Java 9 and later, a new implementation of Clock can capture the current moment up to that nanosecond resolution. But “your mileage may vary”. The actual resolution, and the actual accuracy, depend on the host hardware clock capability.

    Instant instant = Instant.now();
    

    2016-01-02T12:34:56.123456789Z

    Java 8

    Same as for Java 9, java.time classes support up to nanosecond resolution.

    But the current moment is captured only up to millisecond resolution. That means only three (3) or fewer digits of fractional second. This limit is because of a legacy implementation used for Clock.

    Java 6 & 7

    The old date-time classes first bundled with the earliest versions of Java support only milliseconds resolution. This includes java.util.Date, java.util.Calendar, and java.util.GregorianCalendar. These old classes are also poorly designed, confusing, and troublesome. Avoid them.

    Much of the java.time functionality is back-ported in the ThreeTen-Backport project, and further adapted to Android in the ThreeTenABP project.

    As far as I know these rely upon the same legacy implementation, for only milliseconds resolution.

    Accuracy

    Accuracy and precision always depends on your host hardware clock capability.

    See the Question, How precise is the internal clock of a modern PC?

    As I understand today’s common computer hardware, you cannot expect the current moment will be captured with single nanosecond precision.