Home > Web Front-end > JS Tutorial > How Can I Format JavaScript Datetimes in 12-Hour AM/PM Format?

How Can I Format JavaScript Datetimes in 12-Hour AM/PM Format?

Susan Sarandon
Release: 2024-12-02 04:46:15
Original
821 people have browsed it

How Can I Format JavaScript Datetimes in 12-Hour AM/PM Format?

Formatting JavaScript Datetimes in 12-Hour AM/PM Format

When working with date and time data in JavaScript, it's often necessary to display them in a user-friendly format. One common requirement is to format the time in the 12-hour AM/PM format. Here's how it can be achieved:

function formatAMPM(date) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0' + minutes : minutes;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  return strTime;
}

console.log(formatAMPM(new Date));
Copy after login

In this function:

  1. date is a JavaScript Date object representing the datetime to be formatted.
  2. It retrieves the hours, minutes, and determines the AM/PM designation based on the time.
  3. The hours value is adjusted to the 12-hour clock by taking the modulus of 12 and handling the special case of midnight (0 hours) as 12.
  4. The minutes value is formatted with a leading zero if necessary.
  5. The final formatted time is returned as a string in the "hh:mm AM/PM" format.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template