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).
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();
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
The old date-time classes first bundled with the earliest versions of Java support only milliseconds resolution. This includes
java.util.GregorianCalendar. These old classes are also poorly designed, confusing, and troublesome. Avoid them.
As far as I know these rely upon the same legacy implementation, for only milliseconds resolution.
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.