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:

const date = new Date(value);

The value can be one of the following:

  1. String: A string representing a date and time.
  2. 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).

const date = new Date("2024-10-22"); console.log(date);

Output:

Tue Oct 22 2024 00:00:00 GMT+0000 (Coordinated Universal Time)

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.

const dateTime = new Date("2024-10-22T14:30:00"); console.log(dateTime);

Output:

Tue Oct 22 2024 14:30:00 GMT+0000 (Coordinated Universal Time)

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.

const dateFromMs = new Date(1700000000000); console.log(dateFromMs);

Output:

Sat Nov 04 2023 22:46:40 GMT+0000 (Coordinated Universal Time)

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:

const customDate = new Date("October 22, 2024 15:45:00"); console.log(customDate);

Output:

Tue Oct 22 2024 15:45:00 GMT+0000 (Coordinated Universal Time)

Explanation:

  • The string "October 22, 2024 15:45:00" is recognized as a valid date string and results in the creation of a Date 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.

const invalidDate = new Date("invalid-date-string"); console.log(invalidDate);

Output:

Invalid Date

Summary

  • The new Date(value) function creates a Date 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, the Date object will be "Invalid Date".