tl;dr
Duration.ofHours( 11L )
.plusMinutes( 29L )
.plusSeconds( 54L )
.plusMillis( 999L )
.toMillis()
41394999
Span-of-time versus Time-of-day
Your Question is confused. A time-of-day without a date makes no sense in comparison to UTC. A count of milliseconds since the Unix epoch reference date of 1970-01-01T00:00:00Z
is for tracking the date and the time-of-day.
I suspect you are actually dealing with a span of time, and mishandling that as a time-of-day. One is meant for the timeline, the other is not.
Duration
The java.time classes bundled with Java 8 and later include Duration
for handling such spans of time unattached to the timeline.
These methods take long
data type, hence the trailing L
.
Duration d = Duration.ofHours( 11L ).plusMinutes( 29L ).plusSeconds( 54L ).plusMillis( 999L ) ;
Count of milliseconds
You asked for a count of milliseconds, so here you go. Beware of data loss, as a Duration
carries a finer resolution of nanoseconds, so you would be lopping off any finer fraction of a second when converting to milliseconds.
long millis = d.toMillis() ; // Converts this duration to the total length in milliseconds.
41394999
But I suggest you not represent spans of time nor moments on the timeline using a count-of-milliseconds. Better to use objects or standardized text; read on.
ISO 8601
The ISO 8601 standard defines practical unambiguous formats for representing date-time values as text.
This includes representation of durations. The format is PnYnMnDTnHnMnS
where the P
marks the beginning while the T
separates any years-months-days portion from any hours-minutes-seconds portion.
The java.time classes use the standard formats by default in their parse
and toString
methods.
String output = d.toString() ;
PT11H29M54.999S
See this code run live at IdeOne.com.
You can directly parse such strings in java.time.
Duration d = Duration.parse( "PT11H29M54.999S" ) ;
I suggest using this format whenever possible, certainly when exchanging data between systems.
While working inside Java, pass Duration
objects around rather than mere text.
Timeline
You can perform date-time math with the Duration
objects. For example, take the current moment in your particular time zone, and add the eleven and a half hours.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;
ZonedDateTime later = now.plus( d ) ;
now.toString(): 2017-09-27T07:23:31.651+13:00[Pacific/Auckland]
later.toString(): 2017-09-27T18:53:26.650+13:00[Pacific/Auckland]
For UTC values, call toInstant
. The Instant
class represents a moment on the timeline in UTC with resolution of nanoseconds (finer than milliseconds).
Instant instant = later.toInstant() ;