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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-30 18:07:11912browse

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

Displaying JavaScript DateTimes in 12-Hour AM/PM Format

Displaying JavaScript datetime objects in the 12-hour format with AM/PM indicators often becomes necessary for user-friendly display. Here's a solution to this common task:

Answer:

The following JavaScript function takes a JavaScript datetime object as input and returns a formatted string in the 12-hour AM/PM format:

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

Usage:

To use this function, pass a JavaScript datetime object to the formatAMPM() function. The output will be a string formatted in the 12-hour AM/PM format.

For example:

console.log(formatAMPM(new Date)); // Output: 10:25 pm

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