How to create a Java Date object of midnight today and midnight tomorrow?
Make use of the streamlined Java 8 LocalDate.now()
functionality to get the current date and employ atStartOfDay()
to derive midnight today. Then, for midnight tomorrow, simply use plusDays(1)
with midnightToday
. Quick, clean, and timezone-observant.
Handling Time Zones
Keep in mind time zones when working with timestamps. It's essential they align correctly with your specific locale:
Working with Java 7 or earlier
If you're working on Java 7 or earlier, using Calendar
might be more verbose but it's definitely still effective:
Using Instant for UTC time
Working with Universal Coordinated Time (UTC) comes in handy for consistency across various time zones, which applies to global services. Instant
in Java 8 was designed for this:
Simplification with Apache Commons Lang
The DateUtils
from Apache Commons Lang can simplify this task, assuming it's part of your project:
This looks simpler and is absolutely more readable.
Beware of Precisions and Pitfalls!
Navigating Daylight Saving Time
Ensure you're wary of the Daylight Saving Time changes since they can cause unexpected results:
Say No to Deprecated Methods!
For Joda-Time users, avoid using DateMidnight
as it is deprecated. Choose this instead:
Leap Seconds? Leap Years? Leap...Frog?
Rarely, additions like leap seconds or other time corrections can ambush your time calculations. Extreme precision required? Check for such anomalies and make sure your code can jump these hurdles.
Was this article helpful?