1

I need to know how to get LocalTime to milliseconds

    LocalTime  lunchTime = LocalTime.parse("01:00:00",
            DateTimeFormatter.ISO_TIME);

If i am going to execute lunchTime.getMinute() i only get 0 and lunchTime.getHour() i only get 1 as an hour. How to get value in milliseconds?

Cameron Little
  • 2,637
  • 16
  • 29
anduplats
  • 575
  • 1
  • 7
  • 16
  • The getMinute() and getHour() only gives you the Minutes and Hours the time is showing. So your results are correct. If you want to have the current time in milliseconds you have to calculate that yourself. 1h* 60 for minutes, result*1000 for milliseconds. – funky Apr 04 '20 at 11:27
  • Do you want 0 because the millisecond of second is 0, or 3 600 000 because this is the millisecnod of the day, or the count of milliseconds since the epoch? It’s not clear, so please edit and clarify. – Ole V.V. Apr 04 '20 at 18:07

3 Answers3

4

Try getting nano seconds or seconds and converting to milliseconds (depending on what precision you're dealing with).

lunchTime.toNanoOfDay() / 1e+6
lunchTime.toSecondOfDay() * 1e+3
Cameron Little
  • 2,637
  • 16
  • 29
3

If you want the millisecond of the day (in other words the count of milliseconds since 00:00), there is a ChronoField enum constant exactly for that:

    LocalTime lunchTime = LocalTime.parse("01:00:00");
    int millisecondOfDay = lunchTime.get(ChronoField.MILLI_OF_DAY);
    System.out.println("Lunch is at " + millisecondOfDay + " milliseconds of the day");

Output:

Lunch is at 3600000 milliseconds of the day

(1 AM is probably a funny time for lunch for some, but for the sake of demonstration and of using your own example.)

The date and time classes of java.time generally have got a get method that accepts a TemporalField argument. LocalTime is no exception to this rule. The most common thing to do when calling get() is to pass a ChronoField constant. The method is very versatile for getting values from the date-time object for which no getXxx method is provided.

Doc link: ChronoField.MILLI_OF_DAY

Ole V.V.
  • 65,573
  • 11
  • 96
  • 117
0

You can use System.currentTimeMillis(), refer https://currentmillis.com/

Also, please refer https://stackoverflow.com/a/26637209/1270989 to followup on parsing date in your choice of format.

Also, if you trying to get local time in your timezone from an application running in different timezone please follow comment https://stackoverflow.com/a/319398/1270989

Rupesh
  • 2,357
  • 1
  • 23
  • 39