Skip to content
Advertisement

How to display time in required format?

I need to display time in HH:MM AM/PM format. date format :

new Date(2015, 4, 21, 19, 30, 0),

function to convert date in HH:MM format:

  function conertTime(time){
    var localeSpecificTime = time.toLocaleTimeString();
    return localeSpecificTime.replace(/:d+ /, ' ');
}

Advertisement

Answer

You can format the time using Date.prototype.toLocaleTimeString(). The documentation includes examples of options you can pass-in.

If hour12 is false, the time will be rendered in 24-hour time and the meridiem will not be included.

const
  date = new Date(2015, 4, 21, 19, 30, 0),
  formatted = date.toLocaleTimeString('en-US', {
    hour: '2-digit',
    minute: '2-digit',
    hour12: true
  });

console.log(formatted);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement