How to get the current time of microsecond accuracy

How to get the current time of microsecond accuracy in Java 8?

String pattern = "yyyy-MM-dd HH:mm:ss.SSSSSS";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern, Locale.getDefault())
                                                       .withZone(ZoneId.systemDefault());
System.out.println(LocalDateTime.now().format(dateTimeFormatter));

Java 9 or above can, how to do Java 8?


tl;dr

Java 9+ captures current moment in microseconds, while Java 8 captures in mere milliseconds.

ZonedDateTime
.now()  // Uses JVM’s current default time zone.
.format(
    DateTimeFormatter
    .ofLocalizedDateTime( FormatStyle.FULL ) // Uses JVM’s current default locale.
)

ZonedDateTime.now

I cannot image a scenario where calling LocalDateTime.now() is the right thing to do. That class cannot represent a moment as it lacks the context of a time zone or offset. Use ZonedDateTime.

ZonedDateTime zdt = ZonedDateTime.now( ZoneId.systemDefault() ) ;

In Java 8, the moment was captured with a resolution of milliseconds. In Java 9+, microseconds. In all versions, the java.time types are capable of representing nanoseconds, but conventional computers lack the hardware clocks to accurately capture current moment in nanos.

Generate text representing that object’s value in standard ISO 8601 format extended by appending the name of the time zone in square brackets.

String output = zdt.toString() ;

Generate localized text.

Locale locale = Locale.CANADA_FRENCH ;  // Or Locale.getDefault()
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.LONG ).withLocale( locale ) ;
String output = zdt.format( f ) ;