Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display current time in 12 hour format with AM/PM

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"; } 
like image 509
ronan Avatar asked Sep 11 '13 06:09

ronan


People also ask

How do you format am and pm in time?

From 0:00 (midnight) to 0:59, add 12 hours and use am. From 1:00 to 11:59, just add am after the time. From 12:00 to 12:59, just add pm after the time. From 13:00 to 0:00, subtract 12 hours and use pm.

How do you display JavaScript datetime in 24 hour am pm format?

You have the formatAMPM function, which will take a JavaScript date object as a parameter. Call getHours to get the hours in the 24-hour format in the function and minutes to get the minutes. Then, create the ampm variable and set it to am or pm depending on the value of hours.


2 Answers

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

like image 161
Subhrajyoti Majumder Avatar answered Oct 21 '22 13:10

Subhrajyoti Majumder


Use this SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");

enter image description here

Java docs for SimpleDateFormat

like image 37
Tarsem Singh Avatar answered Oct 21 '22 14:10

Tarsem Singh