Date in JavaScript-tutorial
In JavaScript, you can manage dates and times easily using the built-in Date object.
The Date object lets you create, format, and work with dates and times in different ways.
Ways to Create a Data Object
JavaScript's Date constructor supports multiple ways to crate a date
Example: Display Current Date and Time
Output
.webp)
Example: Print Current Time Only
Output
.webp)
Example: Digital Clock Example
Display a live updating digital clock using setTimeout and JavaScript
Output
.webp)
Ways to Create a Data Object
JavaScript's Date constructor supports multiple ways to crate a date
Method | Description | Example |
---|---|---|
new Date() | Current date and time | const now = new Date(); |
new Date(milliseconds) | Date from milliseconds since Jan 1, 1970 | new Date(1625480000000) |
new Date(dateString) | Date from a string | new Date("2023-10-29T12:00:00") |
new Date(year, month, day, hours, minutes, seconds, ms) | Specific date and time | new Date(2023, 4, 15, 12, 30, 0) |
Note: Month is 0-based, so 4 is May.
Example: Display Current Date and Time
<html>
<body> Current Date and Time: <span id="txt"></span> <script> var today = new Date(); document.getElementById('txt').innerHTML = today; </script></body>
</html>
Output
.webp)
Example: Print Current Time Only
<html>
<body> Current Time: <span id="txt"></span> <script> var today = new Date(); var h = today.getHours(); var m = today.getMinutes(); var s = today.getSeconds(); document.getElementById('txt').innerHTML = h + ":" + m + ":" + s; </script></body>
</html>
Output
.webp)
Example: Digital Clock Example
Display a live updating digital clock using setTimeout and JavaScript
<html>
<body> Current Time: <span id="txt"></span> <script> window.onload = function () { getTime(); } function getTime() { var today = new Date(); var h = today.getHours(); var m = today.getMinutes(); var s = today.getSeconds(); m = checkTime(m); s = checkTime(s); document.getElementById('txt').innerHTML = h + ":" + m + ":" + s; setTimeout(getTime, 1000); } function checkTime(i) { return (i < 10) ? "0" + i : i; } </script></body>
</html>
Output
.webp)
Key Point
- Use the Date object to get current date and time.
- Create specific dates by passing milliseconds, date strings, or detailed values.
- Build digital clocks with JavaScript easily.