Print current day and time using HTML and JavaScript
The task is to print the system’s current day and time in the following format(Time in hours, minutes and milliseconds).
Approach:
Use getDay() function to create an array of days in a week. It returns a number of day like 0 for Sunday, 1 for Monday and so on). Convert it into AM or PM using ternary operator.
Use getHours() method to get the hour value between 0 to 23. It returns an integer value.
Minutes and milliseconds were printed using getMinutes() and getMilliseconds() functions respectively.
Example:
<!DOCTYPE html> <html> <head> <title> print current day and time </title> </head> <body> <script type="text/javascript"> var myDate = new Date(); var myDay = myDate.getDay(); // Array of days. var weekday = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ]; document.write("Today is : " + weekday[myDay]); document.write("<br/>"); // get hour value. var hours = myDate.getHours(); var ampm = hours >= 12 ? 'PM' : 'AM'; hours = hours % 12; hours = hours ? hours : 12; var minutes = myDate.getMinutes(); minutes = minutes < 10 ? '0' + minutes : minutes; var myTime = hours + " " + ampm + " : " + minutes + " : " + myDate.getMilliseconds(); document.write("\tCurrent time is : " + myTime); </script> </body> </html> |
Output:

Recommended Posts:
- How to get the current date and time in seconds?
- How to get the current date in JavaScript ?
- How to get the first and last date of current month using JavaScript ?
- How to get current formatted date dd/mm/yyyy in JavaScript ?
- How to close current tab in a browser window using JavaScript?
- How to get current formatted date dd/mm/yyyy in Javascript and append it to an input?
- How to remove time from date using JavaScript ?
- JavaScript | Responsive time of an event
- JavaScript | Call a function after a fixed time
- JavaScript | Program to generate one-time password (OTP)
- How to measure time taken by a function to execute using JavaScript?
- HTML | <time> Tag
- HTML | DOM Time Object
- HTML | DOM Input Time Object
- HTML | DOM Time dateTime Property
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



