乐闻世界logo
搜索文章和话题

How do you display JavaScript datetime in 12 hour AM/PM format?

1个答案

1

In JavaScript, to display date and time in 12-hour AM/PM format, you can use the built-in Date object and format it accordingly. Here are the specific steps and examples:

  1. Create a Date object: First, you need a Date object. This can be the current date and time or a specific date and time.
javascript
var now = new Date();
  1. Extract date and time components: You need to extract hours, minutes, seconds, and other components from the Date object.
javascript
var hours = now.getHours(); var minutes = now.getMinutes(); var seconds = now.getSeconds();
  1. Convert to 12-hour format: By default, the getHours() method returns an hour value between 0 and 23. You need to convert it to a 12-hour format and determine whether it's AM or PM.
javascript
var ampm = hours >= 12 ? 'PM' : 'AM'; hours = hours % 12; hours = hours ? hours : 12; // Convert 0-hour to 12
  1. Format minutes and seconds: For better readability, it's common to format minutes and seconds to always display two digits.
javascript
minutes = minutes < 10 ? '0' + minutes : minutes; seconds = seconds < 10 ? '0' + seconds : seconds;
  1. Combine the final time string: Combine the above parts into the final time string.
javascript
var strTime = hours + ':' + minutes + ':' + seconds + ' ' + ampm;
  1. Output the result: You can use console.log to output the time or display it on a web page.
javascript
console.log(strTime);

Complete Example Code

javascript
function formatAMPM(date) { var hours = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); var ampm = hours >= 12 ? 'PM' : 'AM'; hours = hours % 12; hours = hours ? hours : 12; // Convert 0-hour to 12 minutes = minutes < 10 ? '0' + minutes : minutes; seconds = seconds < 10 ? '0' + seconds : seconds; var strTime = hours + ':' + minutes + ':' + seconds + ' ' + ampm; return strTime; } var now = new Date(); console.log(formatAMPM(now));

This code defines a formatAMPM function that takes a Date object and returns a formatted time string in 12-hour AM/PM format. You can replace now with any valid date, and the function will correctly return the formatted time.

2024年6月29日 12:07 回复

你的答案