JavaScript uses the 24-hour format as default for DateTime. However, daytime in JavaScript can be displayed in 12 hour AM/PM format using several approaches. We will look into a couple in this article.
Approach 1:
In this approach, we will change the DateTime format by only using native methods. Simply put, we will apply modulo “%” operator to find the hour in 12-hour format and use conditional “?:” operator to apply “AM” or “PM”.
Program:
<!DOCTYPE html> < html > < body > < center > < h1 style = "color:green" > GeeksforGeeks </ h1 > < p > Click the button to change the format using Native method. </ p > < div id = "old_time" ></ div > < script > // JavaScript Program to display // current time in 24-hour format var date = new Date(); var hours = (date.getHours() < 10 ? '0' : '') + date.getHours(); var minutes = (date.getMinutes() < 10 ? '0' : '') + date.getMinutes(); var div = document .getElementById('old_time'); div.innerHTML = hours + ":" + minutes; </script> < button onclick = "myFunction()" > Change </ button > < p id = "change" ></ p > < script > // JavaScript function to // Display 12 hour format function myFunction() { var date = new Date(); var hours = date.getHours(); var minutes = date.getMinutes(); // Check whether AM or PM var 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; document.getElementById("change") .innerHTML = hours + ':' + minutes + ' ' + newformat; } </script> </ center > </ body > </ html > |
Before:
After:
Approach 2:
In this approach, we will utilize an inbuilt method toLocaleString() to change the format of given date into AM-PM format.
toLocaleString(): It 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]])
Program:
<!DOCTYPE html> <html> <body> <center> <h1 style= "color:green" >GeeksforGeeks</h1> <p>Click the button to change the format.</p> <div id= "old_time" ></div> <script> var date = new Date(); var hours = (date.getHours() < 10 ? '0' : '' ) + date.getHours(); var minutes = (date.getMinutes() < 10 ? '0' : '' ) + date.getMinutes(); var div = document.getElementById( 'old_time' ); div.innerHTML = hours + ":" + minutes; </script> <button onclick= "myFunction()" > Change </button> <p id= "change" ></p> <script> var now = new Date(); var hours = now.getHours(); function myFunction() { var d = new Date(); var n = d.toLocaleString([], { hour: '2-digit' , minute: '2-digit' }); document.getElementById( "change" ).innerHTML = n; } </script> </center> </body> </html> |
Before:
After: