Home > Back-end >  Get millisecond of LocalTime
Get millisecond of LocalTime

Time:11-14

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?

CodePudding user response:

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

CodePudding user response:

What I wrote is not related to LocalTime, but there may be something useful.

 //Getting the current date
      Date date = new Date();
      //This method returns the time in millis
      long timeMilli = date.getTime();
      System.out.println("Time in milliseconds using Date class: "   timeMilli);

      //creating Calendar instance
      Calendar calendar = Calendar.getInstance();
      //Returns current time in millis
      long timeMilli2 = calendar.getTimeInMillis();
      System.out.println("Time in milliseconds using Calendar: "   timeMilli2);
      
      //Java 8 - toEpochMilli() method of ZonedDateTime
      System.out.println("Getting time in milliseconds in Java 8: "   
      ZonedDateTime.now().toInstant().toEpochMilli());
  •  Tags:  
  • java
  • Related