Home >Web Front-end >JS Tutorial >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:
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!