I have a given LocalTime instance and I just need to get the millisecond value.
For example, to get the hour value I call myLocalTime.getHour(); and to get the minute value I call myLocalTime.getMinute();. But it seems like there is no function to get the millisecond… how do I get it?
>Solution :
Just use getNano() and then divide by a million (the number of nanoseconds in a millisecond). You can use TimeUnit to obtain that "a million" in a more programmatic way, or Duration:
Complete example:
import java.time.Duration;
import java.time.LocalTime;
public class Test {
public static void main(String[] args) throws Exception {
long nanosPerMillisecond = Duration.ofMillis(1).toNanos();
LocalTime now = LocalTime.now();
System.out.println(now);
System.out.println(now.getNano() / nanosPerMillisecond);
}
}
Sample output:
19:28:46.733865200
733