Home >Web Front-end >JS Tutorial >How to Format a JavaScript Datetime Object in 12-Hour AM/PM Format?

How to Format a JavaScript Datetime Object in 12-Hour AM/PM Format?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-09 18:38:11503browse

How to Format a JavaScript Datetime Object in 12-Hour AM/PM Format?

Formatting JavaScript Datetime in 12 Hour AM/PM Format

To display a JavaScript datetime object in the 12 hour format, here's a simple and efficient approach:

Solution:

function formatAMPM(date) {<br>  // Extract hours and minutes from the date object<br>  var hours = date.getHours();<br>  var minutes = date.getMinutes();</p><p>// Determine AM/PM based on hours<br>  var ampm = hours >= 12 ? 'pm' : 'am';</p>
<p>// Convert 24-hour format to 12-hour format<br>  hours = hours % 12;<br>  hours = hours ? hours : 12; // Handle midnight as 12 AM</p>
<p>// Format minutes to include a leading zero for hours less than 10<br>  minutes = minutes < 10 ? '0' minutes : minutes;</p><p>// Construct and return the 12-hour time string<br>  var strTime = hours   ':'   minutes   ' '   ampm;<br>  return strTime;<br>}<br>

Usage:

To use this function, simply pass a JavaScript Date object as an argument to the formatAMPM function. For example:

var now = new Date();
console.log(formatAMPM(now));

This will print the current time in 12-hour AM/PM format, such as "09:30 pm".

The above is the detailed content of How to Format a JavaScript Datetime Object in 12-Hour AM/PM Format?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn