Sometimes, we may want to display a JavaScript date-time in 1 hour AM/PM format.
In this article, we’ll look at how to format a JavaScript date-time into 12 hour AM/PM format.
Create Our Own Function
One way to format a JavaScript date-time into 12 hour AM/PM format is to create our own function.
For instance, we can write:
const formatAMPM = (date) => {
let hours = date.getHours();
let minutes = date.getMinutes();
let ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes.toString().padStart(2, '0');
let strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
console.log(formatAMPM(new Date(2021, 1, 1)));
We have the formatAMPM
function that takes a JavaScript date
object as a parameter.
In the function, we call getHours
tio get the hours in 24 hour format.
minutes
get the minutes.
Then we create the ampm
variable and it to 'am'
or 'pm'
according to the value of hours
.
And then we change the hours
to 12 hour format by using the %
operator to get the remainder when divided by 12.
Next, we convert minutes
to a string with toString
and call padStart
to pad a string with 0 if it’s one digit.
Finally, we put it all together with strTime
.
So when we log the date, we get:
12:00 am
Date.prototype.toLocaleString
To make formatting a date-time to AM/PM format easier, we can use the toLocaleString
method.
For instance, we can write:
const str = new Date(2021, 1, 1).toLocaleString('en-US', {
hour: 'numeric',
minute: 'numeric',
hour12: true
})
console.log(str);
We call toLocaleString
on our date object with the locale and an object with some options.
The hour
property is set to 'numeric'
to display the hours in numeric format.
This is the same with minute
.
hour12
displays the hours in 12-hour format.
So str
is ‘1’2:00 AM’
as a result.
Date.prototype.toLocaleTimeString
We can replace toLocaleString
with toLocaleTimeString
and get the same result.
For instance, we can write:
const str = new Date(2021, 1, 1).toLocaleTimeString('en-US', {
hour: 'numeric',
minute: 'numeric',
hour12: true
})
console.log(str);
And we get the same result.
moment.js
We can also use moment.js to format a date object into a 12-hour date-time format.
To do this, we call the format
method.
For example, we can write:
const str = moment(new Date(2021, 1, 1)).format('hh:mm a')
console.log(str);
And we get the same result as before.
a
adds the AM/PM.
hh
is the formatting code for a 2 digit hour.
mm
is the formatting code for a 2 digit minute.
Conclusion
We can format a JavaScript date-time to 12-hour format with vanilla JavaScript or moment.js.