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"; }
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.
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.
Easiest way to get it by using date pattern - h:mm a
, where
Code snippet :
DateFormat dateFormat = new SimpleDateFormat("hh:mm a");
Read more on documentation - SimpleDateFormat java 7
Use this SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");
Java docs for SimpleDateFormat
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With