Explain Codes LogoExplain Codes Logo

Display current time in 12 hour format with AM/PM

java
date-formatting
time-zone
locale
Nikita BarsukovbyNikita Barsukov·Oct 4, 2024
TLDR

To quickly display time in a 12-hour format using Java, apply SimpleDateFormat along with Calendar:

SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss a"); System.out.println(format.format(Calendar.getInstance().getTime()));

This command will output the time in this format 08:15:42 PM.

Utilizing SimpleDateFormat

Display time correctly by using hh for hour, mm for minute, ss for second, and a for the AM/PM marker in Java's SimpleDateFormat. This will facilitate your audience's understanding, especially if they are familiar with a 12-hour clock format.

Incorporating time zone considerations

Remember to account for the user's time zone when displaying time. Use Calendar.getInstance() to automatically adjust to the user's time zone. For global use, add customized time zones for localized times with setTimeZone:

TimeZone timeZone = TimeZone.getTimeZone("GMT+5:30"); format.setTimeZone(timeZone);

Let's reduce errors by making sure the time suits all time zones.

Adapting to language and cultural formatting

In setting time formats, respect your user's cultural and linguistic settings. Some locales prefer a 12-hour clock without leading zeros: h:mm:ss a. To accommodate these preferences, use locale-specific SimpleDateFormat:

Locale locale = new Locale("es", "MX"); // Hola Mexico! format = new SimpleDateFormat("h:mm:ss a", locale);

Giving some locale love! 🎉

Incorporating robust error handling

Good code isn't just about doing things right, it's also about doing the right things when things go awry. Catch and handle ParseExceptions and potential NullPointerExceptions to ensure your time formatting is as reliable as it is nifty:

try { String currentTime = format.format(Calendar.getInstance().getTime()); System.out.println("Current Time: " + currentTime); } catch (Exception e) { e.printStackTrace(); // Or blame it on the timezone! 😄 }

That's not an error; it's a feature!

Activating validation through testing

Ensure your time formatting withstands the test of.. well, time zones and locales. Nothing catches issues earlier than a good-old test drive:

formatter.setTimeZone(TimeZone.getTimeZone("EST")); System.out.println("EST Time: " + formatter.format(new Date()));

If it's wrong, it's probably a leap second 😉

Advancing to DateTimeFormatter

For those lucky folks on Java 8 or later, bid goodbye to SimpleDateFormat and embrace DateTimeFormatter for its immutable and thread-safe properties:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss a"); System.out.println(LocalDateTime.now().format(formatter));

Is it a SimpleDateFormat, is it a DateTimeFormatter... No, it's Java 8!