JavaScript Dates

The Date object in JavaScript provides methods to work with dates and times. You can create dates, retrieve components, and format them for display.

Key Topics

Creating Dates

You can create a Date object using the constructor with no arguments (current date/time) or by providing specific date/time values.

let now = new Date();
console.log(now);

Output

> Current date and time (e.g., "Mon Jun 21 2021 10:20:30 GMT+...")

Explanation: Calling new Date() without arguments returns the current date and time.

Date Initialization Methods

You can initialize dates using strings, year/month/day, or millisecond values since January 1, 1970.

let specificDate = new Date("2021-06-21");
console.log(specificDate);

Output

> Mon Jun 21 2021 00:00:00 GMT+...

Explanation: Providing a date string creates a Date object set to that specific date.

JavaScript Usage in DOM

This DOM-based example shows how to display the current date on a webpage.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dates in DOM</title>
</head>
<body>
    <h1>Date Demo</h1>
    <button onclick="showDate()">Show Date</button>
    <p id="display"></p>

    <script>
        function showDate() {
            let d = new Date();
            document.getElementById("display").textContent = d.toString();
        }
    </script>
</body>
</html>

Key Takeaways

  • Creating Dates: Use new Date() for current or specified dates.
  • Initialization Methods: Create dates from strings, components, or timestamps.
  • DOM Integration: Display dynamic date and time information on webpages.