TL;DR Use Duration
, not LocalTime
. See end of answer.
Question code is incorrect
Be aware that the 4th argument to LocalTime.of()
is nanosecond, not millisecond, which you'd see if you print localTime
:
System.out.println(localTime); // prints: 00:27:10.000000190
So you need to change your code to:
LocalTime localTime = LocalTime.of(0, minutes, seconds, milliseconds * 1000000);
System.out.println(localTime); // prints: 00:27:10.190
Using LocalTime
If you wanted the milliseconds
value back, call getLong(TemporalField field)
with ChronoField.MILLI_OF_SECOND
:
localTime.getLong(ChronoField.MILLI_OF_SECOND) // returns 190
To gain total number of milliseconds, i.e. not just the milliseconds
value, use ChronoField.MILLI_OF_DAY
as argument:
localTime.getLong(ChronoField.MILLI_OF_DAY) // returns 1630190
Using Duration
However, since the input is named lapTime
, the LocalTime
class is not the right tool for the job. E.g. your code will fail if minutes >= 60.
The right tool is the Duration
class, e.g.
Duration duration = Duration.ofMinutes(minutes).plusSeconds(seconds).plusMillis(milliseconds);
Or:
Duration duration = Duration.ofSeconds(seconds, milliseconds * 1000000).plusMinutes(minutes);
You can then get the milliseconds directly by calling toMillis()
:
duration.toMillis(); // returns 1630190
That works even if the lap time exceeds one hour, e.g.
String lapTime = "127:10.190";
. . .
duration.toMillis(); // returns 7630190
In Java 9+, you can get the millisecond part back easily, by calling toMillisPart()
:
duration.toMillisPart(); // returns 190