JavaScript Date objects allow us to work with dates. Dates are static by default. The computer time is not moving in a Date object, it represents a single moment in time.
You can create a new Date object using the new Date()
constructor. There are 4 ways to create a new date:
// 1. Current date and time
const d1 = new Date();
// 2. From a date string
const d2 = new Date("2022-03-25");
// 3. From specific numbers (year, month, day, hours, minutes, seconds, ms)
const d3 = new Date(2022, 11, 24, 10, 33, 30, 0);
// 4. From milliseconds (since Jan 01, 1970)
const d4 = new Date(1000000000000);
JavaScript will (by default) output dates in full text string format:
const d = new Date();
console.log(d.toString()); // Full format
toDateString(): Returns a readable date (e.g., "Fri Mar 25
2022").toUTCString(): Converts a date to a UTC string (GMT
format).toISOString(): Returns the date in standard ISO format.
| Syntax | Description |
|---|---|
new Date() |
Creates a date object with the current date and time |
new Date(year, month, ...) |
Creates a date object with a specified date and time |
new Date(milliseconds) |
Creates a date object as zero time plus milliseconds |
new Date(date string) |
Creates a date object from a date string |
new Date() to create date instancestoDateString()