Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 29 - JavaScript Date Object

JavaScript's Date object allows you to work with dates and times. You can create, format, and manipulate dates easily.


Explanation

  • The Date object represents a single moment in time in a platform-independent format.
  • You can create a Date object using:
    • new Date(): Current date and time.
    • new Date(year, month, day, hours, minutes, seconds, ms): Specific date.
    • new Date(dateString): From a string.

Example 1: Creating Dates

let currentDate = new Date();
console.log("Current Date:", currentDate);

let specificDate = new Date(2023, 11, 25); // December 25, 2023
console.log("Specific Date:", specificDate);

let fromString = new Date("2024-02-29T15:00:00");
console.log("Date from String:", fromString);
  • Logs the current date, a specific date, and a date created from a string.

Example 2: Getting Date Components

let today = new Date();
console.log("Year:", today.getFullYear());
console.log("Month:", today.getMonth() + 1); // Months are 0-indexed
console.log("Date:", today.getDate());
console.log("Day of Week:", today.getDay()); // 0 = Sunday, 6 = Saturday
console.log("Hours:", today.getHours());
console.log("Minutes:", today.getMinutes());
console.log("Seconds:", today.getSeconds());
  • Retrieves parts of the current date and time.

Example 3: Modifying Dates

let date = new Date();
date.setFullYear(2025);
date.setMonth(0); // January
date.setDate(1);
console.log("Modified Date:", date);
  • Changes the date to January 1, 2025.

Try Your Hand

Steps:

  1. Create a File:

    • Name it lesson29-date.html.
  2. Write the Code:

    • Copy the following code:

      <!DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Lesson 29 - Date Object</title>
      </head>
      <body>
      <script>
         let now = new Date();
         document.write("<h2>Today's Date:</h2>");
         document.write(now.toDateString());
      
         let newYear = new Date(now.getFullYear() + 1, 0, 1);
         document.write("<h3>Next New Year:</h3>");
         document.write(newYear.toDateString());
      </script>
      </body>
      </html>
  3. Save the File.

  4. Open it in a Browser to See the Output.


Experiment

  1. Display how many days are left until your next birthday.
  2. Show the current time and update it every second using setInterval.
  3. Format the date as DD/MM/YYYY.

Key Takeaways

  • Date object allows working with dates and times.
  • Use get and set methods to read or modify dates.
  • Dates can be formatted and manipulated easily.