Print current day and time using HTML and JavaScript
Last Updated :
11 Jul, 2025
Improve
Printing the current day and time using HTML and JavaScript involves dynamically displaying the present date and time on a webpage. JavaScript's Date object is used to retrieve the current day, month, year, and time, which is then embedded in the HTML content.
Approach:
- Retrieve Current Date and Day: Use the new Date() to get the current date and getDay() to retrieve the day's index (0 for Sunday).
- An array of Weekdays: Map the day's index to a weekday array, which contains the names of the days, to display the correct day.
- Get Time Components: Extract hours using getHours() and convert them to 12-hour format. Also, retrieve minutes using getMinutes().
- AM/PM Determination: Determine whether it's AM or PM using a conditional check, adjusting the hour if necessary for the 12-hour format.
- Display Time and Day: Use document.write() to display the current day and formatted time, including the hour, minutes, and milliseconds.
Example: In this example we are following the above-explained approach.
<!DOCTYPE html>
<html>
<head>
<title>
print current day and time
</title>
</head>
<body>
<script type="text/javascript">
let myDate = new Date();
let myDay = myDate.getDay();
// Array of days.
let weekday = ['Sunday', 'Monday', 'Tuesday',
'Wednesday', 'Thursday', 'Friday', 'Saturday'
];
document.write("Today is : " + weekday[myDay]);
document.write("<br/>");
// get hour value.
let hours = myDate.getHours();
let ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12;
let minutes = myDate.getMinutes();
minutes = minutes < 10 ? '0' + minutes : minutes;
let myTime = hours + " " + ampm + " : " + minutes +
" : " + myDate.getMilliseconds();
document.write("\tCurrent time is : " + myTime);
</script>
</body>
</html>
Output:
