The difference between `Date()` and `new Date()` in JavaScript

Posted: 31-05-2024 | Views: 22
The difference between `Date()` and `new Date()` in JavaScript

The difference between Date() and new Date() in JavaScript is primarily in how they are used and what they return:

  1. Date():

    • When called as a function (without the new keyword), Date() returns a string representing the current date and time. This string is in a human-readable format and corresponds to the current date and time in the system's local time zone.
    • Example:
      console.log(Date()); // Outputs something like: "Wed May 30 2024 14:23:15 GMT+0000 (Coordinated Universal Time)"
  2. new Date():

    • When called as a constructor (with the new keyword), new Date() creates a new Date object. This object represents a specific point in time.
    • Example:
      let currentDate = new Date();
      console.log(currentDate); // Outputs something like: 2024-05-30T14:23:15.678Z (an ISO string representation of the current date and time)
    • The Date object created with new Date() has various methods that can be used to manipulate and retrieve specific parts of the date and time, such as getFullYear(), getMonth(), getDate(), etc.
    • Example:
      let date = new Date();
      console.log(date.getFullYear()); // Outputs the current year, e.g., 2024
      console.log(date.getMonth()); // Outputs the current month (0-11)
      console.log(date.getDate()); // Outputs the current day of the month (1-31)

In summary, Date() returns a string of the current date and time, while new Date() creates an instance of the Date object, which provides various methods to work with dates and times.

Add comment