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));
In this function:
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!