Open In App

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

Last Updated : 20 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript uses the 24-hour format as the default for DateTime. However, daytime in JavaScript can be displayed in 12-hour AM/PM format using several approaches.

There are two approaches that will be discussed below:

Approach 1: Using the Native Approach

In this approach, we will change the DateTime format by only using native methods. Simply put, we will apply the modulo “%” operator to find the hour in 12-hour format and use the conditional “?:” operator to apply “AM” or “PM”

Example: In this example, we are determining whether the given time belongs to AM or PM.

Javascript




function changeTimeFormat() {
    let date = new Date();
 
    let hours = date.getHours();
    let minutes = date.getMinutes();
 
    // Check whether AM or PM
    let newformat = hours >= 12 ? 'PM' : 'AM';
 
    // Find current hour in AM-PM Format
    hours = hours % 12;
 
    // To display "0" as "12"
    hours = hours ? hours : 12;
    minutes = minutes < 10 ? '0' + minutes : minutes;
 
    console.log(hours + ':' + minutes + ' ' + newformat);
}
 
changeTimeFormat();


Output

5:34 AM

Approach 2: Using toLocaleString() Method

In this approach, we will utilize an inbuilt method toLocaleString() to change the format of the given date into AM-PM format. toLocaleString() Method returns a string representation of the date Object. The 2 arguments Locale and options allow for customization of the behavior of the method. 

Syntax:

dateObject.toLocaleString([locales[, options]]);

Example: In this example, we are determining whether the given time belongs to AM or PM.

Javascript




function changeTimeFormat() {
    let date = new Date();
    let n = date.toLocaleString([], {
        hour: '2-digit',
        minute: '2-digit'
    });
 
    console.log(n);
}
 
changeTimeFormat();


Output

05:34 AM


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads