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(); |
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(); |
02:07 AM