Skip to content

JavaScript Date Object

The JavaScript Date object provides a way to work with dates and times in JavaScript. You can create Date objects to represent a specific date and time.

With the Date object, you can perform operations like getting the current date and time, converting between different date formats, and calculating the difference between two dates.

Here are some Date objects’ built-in methods that perform various operations on dates and times.

  1. new Date() – This method creates a new Date object with the current date and time.
  2. Date.parse() – This method converts a date string into a timestamp (the number of milliseconds since January 1, 1970, 00:00:00 UTC).
  3. Date.UTC() – This method returns the number of milliseconds between January 1, 1970, 00:00:00 UTC, and a specified date and time.
  4. getDate() – This method returns the day of the month (from 1 to 31) for a specified Date object.
  5. getMonth() – This method returns the month (from 0 to 11) for a specified Date object.
  6. getFullYear() – This method returns the year (four digits for dates between 1000 and 9999) for a specified Date object.
  7. getHours() – This method returns the hour (0 to 23) for a specified Date object.
  8. getMinutes() – This method returns the minutes (0 to 59) for a specified Date object.
  9. getSeconds() – This method returns the seconds (0 to 59) for a specified Date object.
  10. getTime() – This method returns the number of milliseconds since January 1, 1970, 00:00:00 UTC for a specified Date object.

JavaScript Date Object examples

A simple example code shows how to create a Date object and use some of its methods to display the current date and time:

<!DOCTYPE html>
<html>
<body>
<script>
    // Create a new Date object
    const currentDate = new Date();

    // Get the current date and time components
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth() + 1;
    const day = currentDate.getDate();
    const hours = currentDate.getHours();
    const minutes = currentDate.getMinutes();
    const seconds = currentDate.getSeconds();

    // Display the current date and time
    console.log(`The current date is: ${month}/${day}/${year}`);
    console.log(`The current time is: ${hours}:${minutes}:${seconds}`);

</script>
</body>
</html>

Output:

JavaScript Date Object

Comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *