ISO 8601
Your desired format for a time-of-day is standard ISO 8601 format. The java.time classes use ISO 8601 formats by default when parsing/generating String representations of their date-time values.
Nanoseconds
The java.time classes support a resolution up to nanoseconds. The legacy date-time classes they supplant were limited to milliseconds.
LocalTime
The LocalTime
class represents a time-of-day without a date and without a time zone.
Determining the current time-of-day does require a time zone. For any given moment, the time-of-day varies around the globe by zone.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalTime lt = LocalTime.now( z );
Generate a String by calling toString
.
String output = lt.toString(); // 12:34:56.789
In Java 8, capturing the current time is limited to milliseconds. The class can hold up to nanoseconds, but the Clock
implementation has legacy limitations. In Java 9, a new Clock
implementation is capable of capturing the current time in up to nanoseconds (depending on the host computer’s hardware capability).
The Question mentions LocalDateTime
. That class is for a date-time, a date plus a time-of-day. But the class purposely lacks any concept of time zone. Almost never what you want, as a LocalDateTime
does not represent a moment on the timeline. Without the context of a time zone saying "3 PM on Jan 15th this year" has no meaning as 3 PM in Paris Texas is not the same as in Montréal Québec which is not the same as in Auckland New Zealand. Assign a time zone (ZoneId
) to determine an actual moment in a ZonedDateTime
object. For UTC values, just use Instant
.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
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.