78. Extracting the count of milliseconds since midnight
So, we have a date-time (let’s say a LocalDateTime or LocalTime) and we want to know how many milliseconds have passed from midnight to this date-time. Let’s consider that the given date-time is right now:
LocalDateTime now = LocalDateTime.now(); Midnight is relative to now, so we can find the difference as follows:
LocalDateTime midnight = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), 0, 0, 0); Finally, compute the difference in milliseconds between midnight and now. This can be accomplished in several ways, but probably the most concise solution relies on java.time.temporal.ChronoUnit. This API exposes a set of units useful to manipulate a date, time, or date-time including milliseconds:
System.out.println("Millis: " + ChronoUnit.MILLIS.between(midnight, now)); In the bundled code, you can see more examples of ChronoUnit.