tl;dr
LocalTime // Represents a time-of-day, without date and without time zone.
.ofNanoOfDay( // Convert a count of nanoseconds into a time-of-day in a generic 24-hour day, ignoring real-world anomalies such as Daylight Saving Time (DST).
Duration // Class that represents a span-of-time not attached to the timeline.
.of( milliseconds ) // Parse your count of milliseconds as a span-of-time.
.toNanos() // Extract total number of nanoseconds in this span-of-time.
) // Returns a `LocalDate` object.
.toString() // Generate text in standard ISO 8601 format for a time-of-day (*not* recommended by me).
java.time.Duration
The proper class to represent a span-of-time unattached to the timeline with a scale of hours-minutes-seconds is Duration
. For a scale of years-months-days, use Period
.
Duration d = Duration.of( milliseconds ) ;
ISO 8601 format
I suggest you avoid reporting a span-of-time using the time-of-day format of HH:MM:SS. I have seen the inherent ambiguity lead to misinterpretation and confusion in real-world business apps.
There is a standard for reporting such values, defined in ISO 8601: PnYnMnDTnHnMnS
. The P
marks the beginning while the T
separates any year-month-day portion from any hour-minute-second portion.
The java.time classes use the ISO 8601 standard formats by default when parsing/generating strings. This includes the Duration
class.
Duration d = Duration.ofMillis( 5_025_678L ) ;
String output = d.toString() ;
See this code run live at IdeOne.com.
PT1H23M45.678S
These ISO 8601 strings can be parsed as well as generated.
Duration d = Duration.parse( "PT1H23M45.678S" ) ;
Time-of-day format
But if you insist on use time-of-day format for your duration, you can put together such a sting by calling the to…Part
methods on Duration
object.
Duration d = Duration.ofMillis( 5_025_678L ) ;
String output = d.toHoursPart() + ":" + d.toMinutesPart() + ":" + d.toSecondsPart() + "." + TimeUnit.NANOSECONDS.toMillis( d.toNanosPart() ) ;
1:23:45.678
Or we could abuse the LocalTime
class to create your string.
Duration d = Duration.ofMillis( 5_025_678L ) ;
long nanoOfDay = d.toNanos() ;
LocalTime localTimeBogus = LocalTime.ofNanoOfDay( nanoOfDay ) ;
String output = localTimeBogus.toString() ;
Again, you can see this code run live at IdeOne.com.
01:23:45.678