Javascript new date
The Date
object in JavaScript!
The Date
object is a built-in object that represents a date and time. You can create a new Date
object using the new Date()
constructor, which returns a Date
object with the current date and time.
Here are some ways to create a new Date
object:
-
Default constructor:
new Date()
This creates aDate
object with the current date and time.const now = new Date(); console.log(now); // Output: current date and time
-
Constructor with arguments:
new Date(year, month, day, hours, minutes, seconds, milliseconds)
This creates aDate
object with the specified date and time.const date = new Date(2022, 5, 12, 14, 30, 0, 0); console.log(date); // Output: June 12, 2022 02:30:00.000
Note that the
month
argument is 0-based, meaning January is 0 and December is 11. -
Constructor with a string:
new Date(string)
This creates aDate
object from a string in the formatYYYY-MM-DDTHH:MM:SS.SSSZ
.const date = new Date('2022-06-12T14:30:00.000Z'); console.log(date); // Output: June 12, 2022 02:30:00.000
-
Constructor with a timestamp:
new Date(timestamp)
This creates aDate
object from a timestamp in milliseconds since the Unix epoch (January 1, 1970, 00:00:00 UTC).const timestamp = 1652336400000; const date = new Date(timestamp); console.log(date); // Output: June 12, 2022 02:30:00.000
Once you have a
Date
object, you can access various properties and methods to work with the date and time. Some common properties and methods include:
getFullYear()
: Returns the full year (e.g., 2022)getMonth()
: Returns the month (0-based, e.g., 5 for June)getDate()
: Returns the day of the month (1-31)getHours()
: Returns the hour (0-23)getMinutes()
: Returns the minute (0-59)getSeconds()
: Returns the second (0-59)getTime()
: Returns the timestamp in milliseconds since the Unix epochtoDateString()
: Returns a string representation of the date (e.g., "Sun Jun 12 2022")toLocaleString()
: Returns a string representation of the date and time in the user's locale