JavaScript provides the Date object to work with dates and times. It can store years, months, days, hours, minutes, seconds, and milliseconds.
The Date object represents a single moment in time.
A Date object can be created in several ways.
Different constructors allow different date formats.
| Parameter | Description |
|---|---|
| No Parameter | Current date and time. |
| Value | Milliseconds since 1 Jan 1970. |
| Date String | Date in text format. |
| Year | Year value. |
| Month | 0 to 11. |
| Day | Day of month. |
| Hours | 0 to 23. |
| Minutes | 0 to 59. |
| Seconds | 0 to 59. |
| Milliseconds | 0 to 999. |
Milliseconds are counted from January 1, 1970.
The larger the number, the later the date and time.
A date can also be created using a text string.
JavaScript converts valid date strings into Date objects.
JavaScript accepts different separators while creating date strings.
Common separators include -, /, and ,.
You can specify year, month, day, hour, minute, second, and millisecond.
Remember that months start from 0 (January).
JavaScript supports several date formats.
| Method | Purpose |
|---|---|
| toDateString() | Readable date. |
| toLocaleDateString() | Local date format. |
| toLocaleString() | Local date and time. |
| toLocaleTimeString() | Local time. |
JavaScript supports the ISO 8601 standard format.
Output:
| Method | Description |
|---|---|
| toDateString() | Returns date only. |
| toTimeString() | Returns time only. |
| toUTCString() | Returns UTC date. |
| toGMTString() | Returns GMT format. |
| toISOString() | Returns ISO format. |
| toLocaleString() | Returns local date and time. |
| toLocaleDateString() | Returns local date. |
| toLocaleTimeString() | Returns local time. |
| Constructor | Purpose |
|---|---|
| new Date() | Current date and time |
| new Date(value) | Milliseconds |
| new Date(string) | Date from text |
| new Date(y,m,d) | Custom date |
Which statement creates the current date and time in JavaScript?