Reader small image

You're reading from  Java Coding Problems - Second Edition

Product typeBook
Published inMar 2024
PublisherPackt
ISBN-139781837633944
Edition2nd Edition
Right arrow
Author (1)
Anghel Leonard
Anghel Leonard
author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard

Right arrow

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.

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Java Coding Problems - Second Edition
Published in: Mar 2024Publisher: PacktISBN-13: 9781837633944

Author (1)

author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard