JavaScript Date Set Methods

Date set methods allow you to modify specific parts of a date, such as changing the year, month, day, or even the hour, minute, and second. This helps in dynamically updating date/time values as needed.

Key Topics

Basic Set Methods

Methods like setFullYear(), setMonth(), and setDate() update specific date components.

let d = new Date();
d.setFullYear(2022);
d.setMonth(11); // December since it's 0-based
console.log(d);

Output

> Date object representing Dec 2022 (day/time unchanged)

Explanation: Setting the year to 2022 and month to December modifies the existing date object accordingly.

UTC Set Methods

Similar UTC versions (e.g., setUTCFullYear(), setUTCMonth()) let you change the date based on UTC time.

d.setUTCDate(15);
console.log(d);

Output

> Date object with day set to 15 in UTC context

Explanation: Using UTC set methods changes the date components as if you were operating in UTC time.

JavaScript Usage in DOM

This DOM-based example allows you to change the date components of a displayed date interactively on the webpage.

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

    <script>
        let currentDate = new Date();
        document.getElementById("display").textContent = currentDate.toString();

        function changeYear() {
            currentDate.setFullYear(currentDate.getFullYear() + 1);
            document.getElementById("display").textContent = currentDate.toString();
        }
    </script>
</body>
</html>

Key Takeaways

  • Set Methods: setFullYear(), setMonth(), setDate() adjust date parts.
  • UTC Methods: setUTCFullYear(), setUTCMonth(), etc., modify date based on UTC time.
  • DOM Integration: Update and display altered date values dynamically on webpages.