JavaScript new Date(value) function
The new Date(value)
function in JavaScript creates a new Date
object from a given value, where the value
can be a valid string representation of a date, a number (representing milliseconds since the Unix Epoch), or other valid formats.
Syntax:
The value
can be one of the following:
- String: A string representing a date and time.
- Number: The number of milliseconds since January 1, 1970, 00:00:00 UTC (also called the Unix Epoch).
Examples:
1. Using a Date String
You can pass a date string in a format recognized by JavaScript (ISO format is recommended).
Output:
Explanation:
- The date string
"2024-10-22"
is parsed as October 22, 2024, and the time defaults to midnight (00:00:00).
2. Using a Date and Time String
You can pass a more detailed string specifying both the date and time.
Output:
Explanation:
- The string
"2024-10-22T14:30:00"
specifies both the date (October 22, 2024) and the time (14:30:00 or 2:30 PM in 24-hour format).
3. Using a Number (Milliseconds since Epoch)
You can pass a number that represents the number of milliseconds since January 1, 1970.
Output:
Explanation:
- The number
1700000000000
represents the number of milliseconds since January 1, 1970. This translates to November 4, 2023, at 22:46:40 UTC.
4. Using Different Date Formats
JavaScript can parse other date formats, but the ISO 8601 format is recommended for consistency across browsers. Here's an example with a different date format:
Output:
Explanation:
- The string
"October 22, 2024 15:45:00"
is recognized as a valid date string and results in the creation of aDate
object representing October 22, 2024, at 3:45 PM.
Invalid Date Example
If the value
passed to new Date(value)
is not a valid date or cannot be parsed, JavaScript will return an "Invalid Date" object.
Output:
Summary
- The
new Date(value)
function creates aDate
object from the given value. - If
value
is a string, it must be in a recognized date format (ISO 8601 recommended). - If
value
is a number, it represents milliseconds since the Unix Epoch (January 1, 1970). - If the
value
cannot be parsed, theDate
object will be "Invalid Date".