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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-31 19:32:16982browse

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

Displaying JavaScript Datetime in 12-Hour AM/PM Format

JavaScript offers various methods for manipulating dates and times. One common requirement is displaying datetime objects in a human-readable format, specifically in the 12-hour AM/PM format. This format is prevalent in many countries and applications.

Solution:

To display a JavaScript datetime object in the 12-hour AM/PM format, we can utilize the following code:

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;
}

This function takes a JavaScript Date object as input and processes it as follows:

  1. Extract the hours and minutes.
  2. Determine whether it is AM or PM based on the hour.
  3. Convert 24-hour time to 12-hour time by taking the modulus with 12.
  4. Handle the special case where the hour is 0 by setting it to 12 for AM.
  5. Ensure that the minutes are always displayed in the two-digit format.
  6. Combine the formatted hour, minutes, and AM/PM into a string.

By using this function, you can easily convert JavaScript datetime objects into human-readable 12-hour AM/PM strings.

The above is the detailed content of How to Display JavaScript Datetime 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