The Date object
- Node.js course
- Intermediate
- Lesson 94/116
- 4 min
Learn date and time with the Date object.
The Date object
In JavaScript date and time are represented by the Date object. new Date() gives the current moment; new Date("2024-03-15") parses a specific date. In Node.js Date is global; you do not need to import it.
Dates are stored internally as milliseconds since 1 January 1970. Date.now() returns this number directly; it is fast for timing without parsing a date. The Z suffix in new Date("2024-03-15T00:00:00Z") marks UTC; the date then becomes timezone-independent. The toISOString() method returns the date as a string in the form 2024-03-15T00:00:00.000Z; this is the standard format for logs and data exchange.
Parsing dates
To parse a date from a string you use new Date("..."). Accepted formats: 2024-03-15 (date only), 2024-03-15T10:30:00 (date and time), 2024-03-15T10:30:00Z (UTC).
A non-UTC string is interpreted in the local timezone; this can give different results on different machines. When testing, always use the Z suffix to make output deterministic. The output of toISOString() is always UTC; toString() writes the local timezone and varies by zone. In this lesson we parse UTC dates and print with toISOString(); the next lesson teaches local components (getDate, getMonth).
Practice Parse and print a date
Define a UTC date with const date = new Date("2024-03-15T00:00:00Z");. Print in ISO format with console.log(date.toISOString()).
Starter code
// Define a UTC date
// write here
// Print in ISO format
// write hereSample solution
const date = new Date("2024-03-15T00:00:00Z");
console.log(date.toISOString());Expected output
2024-03-15T00:00:00.000Z
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does new Date("2024-03-15T00:00:00Z") create?
new Date("2024-03-15T00:00:00Z")- A number
- Bir Date nesnesi Correct answer
- Bir dize
- Bir dizi
Explanation: new Date() returns a Date object.
2 Complete the Date construction
const date = new ____("2024-03-15T00:00:00Z");
const date = new Date("2024-03-15T00:00:00Z");
Explanation: new Date creates a date object.
3 Match each piece to its role
| Term | Meaning |
|---|---|
new Date() |
Creates a date object |
Date.now() |
Gives millisecond count |
toISOString() |
Gives ISO-format string |
"Z" suffix |
Marks UTC |