Java: getMinutes and getHours
Access hours and minutes from a Java Date object by resorting to the Calendar class, as the Date's own getHours() and getMinutes() are considered obsolete. Here's a starter:
Note: Opt for Calendar.HOUR for the more traditional 12-hour format, and Calendar.HOUR_OF_DAY for the all-inclusive 24-hour format. Don't forget to swap out date with your Date instance.
Java 8 and java.time
The java.time package, introduced in Java 8, improves handling of dates and times:
Java Evolution: This approach is ISO-8601 standard-friendly and helps prevent those awkward time zone mix ups. Kind of like when you call your Australian friend at 3 AM instead of PM.
Time zones? No problem!
The java.time package offers ZonedDateTime, which effortlessly handles time zones:
Avoid the default time zone surprises, and explicitly specify the time zone:
Time traveling with ThreeTen-Extra
In addition to java.time, the ThreeTen-Extra project offers more date time functionalities:
Evading outdated methods
Old code may reveal deprecated methods like Date.getHours() or Date.getMinutes(). Upgrading to java.time or using the Joda-Time library (pre-Java 8), helps keep your code in the modern era:
JDBC 4.2+ compatibility
Working with java.time types becomes a breeze with JDBC 4.2 compliant drivers, which facilitates direct mapping with databases:
This direct mapping keeps things DRY, meaning less room for errors.
Month Hygiene 101
Keep in mind that with Calendar: the months are zero-based, so add one to make life easier:
Month offsets: Easy to overlook but could lead to those facepalm off-by-one errors.
24h vs 12h with Calendar
Whether your app calls for 24-hour or 12-hour format, Calendar has your back:
Knowing the difference saves you from having to Google "What the heck is 1700 hours in normal time?".
Addressing Date's limitations
Directly using Date's methods is discouraged. Instead, Calendar provides a better approach:
Say no to deprecated methods and ambiguous defaults.
For the Joda-Time fans
For those not using Java 8+, Joda-Time is at your service:
Tip: Hold on to your Joda-Time code until the voyage to Java 8 is complete.
Was this article helpful?