Display current time in 12 hour format with AM/PM

ronan picture ronan · Sep 11, 2013 · Viewed 418.4k times · Source

Currently the time displayed as 13:35 PM However I want to display as 12 hour format with AM/PM, i.e 1:35 PM instead of 13:35 PM

The current code is as below

private static final int FOR_HOURS = 3600000;
private static final int FOR_MIN = 60000;
public String getTime(final Model model) {
    SimpleDateFormat formatDate = new SimpleDateFormat("HH:mm a");
    formatDate.setTimeZone(userContext.getUser().getTimeZone());
    model.addAttribute("userCurrentTime", formatDate.format(new Date()));
    final String offsetHours = String.format("%+03d:%02d", userContext.getUser().getTimeZone().getRawOffset()
    / FOR_HOURS, Math.abs(userContext.getUser().getTimeZone().getRawOffset() % FOR_HOURS / FOR_MIN));
    model.addAttribute("offsetHours",
                offsetHours + " " + userContext.getUser().getTimeZone().getDisplayName(Locale.ROOT));
    return "systemclock";
}

Answer

Subhrajyoti Majumder picture Subhrajyoti Majumder · Sep 11, 2013

Easiest way to get it by using date pattern - h:mm a, where

  • h - Hour in am/pm (1-12)
  • m - Minute in hour
  • a - Am/pm marker

Code snippet :

DateFormat dateFormat = new SimpleDateFormat("hh:mm a");

Read more on documentation - SimpleDateFormat java 7