Wednesday, July 3, 2024
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

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments