Monday, June 15, 2026
HomeLanguagesJavascriptHow do you display JavaScript datetime in 12 hour AM/PM format ?

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

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 discuss below:

  • Using the Native Approach
  • Using toLocaleString() Method

Approach 1: Using 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::

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

2:02 AM

Approach 2: Using toLocaleString() Method

In this approach, we will utilize an inbuilt method toLocaleString() to change the format of given date into AM-PM format. 

toLocaleString() Mrthod 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: 

Javascript




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


Output

02:07 AM

RELATED ARTICLES

Most Popular

Dominic
32516 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS