The difference between Date() and new Date() in JavaScript is primarily in how they are used and what they return:
-
Date():- When called as a function (without the
newkeyword),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)"
- When called as a function (without the
-
new Date():- When called as a constructor (with the
newkeyword),new Date()creates a newDateobject. 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
Dateobject created withnew Date()has various methods that can be used to manipulate and retrieve specific parts of the date and time, such asgetFullYear(),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)
- When called as a constructor (with the
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.