I need to display time in HH:MM AM/PM format. date format :
JavaScript
x
1
1
new Date(2015, 4, 21, 19, 30, 0),
function to convert date in HH:MM format:
JavaScript
1
4
1
function conertTime(time){
2
var localeSpecificTime = time.toLocaleTimeString();
3
return localeSpecificTime.replace(/:d+ /, ' ');
4
}
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.
JavaScript
1
9
1
const
2
date = new Date(2015, 4, 21, 19, 30, 0),
3
formatted = date.toLocaleTimeString('en-US', {
4
hour: '2-digit',
5
minute: '2-digit',
6
hour12: true
7
});
8
9
console.log(formatted);