JavaScript new Date(milliseconds) function


The new Date(milliseconds) function in JavaScript creates a new Date object that represents the date and time corresponding to the number of milliseconds since the Unix Epoch (January 1, 1970, 00:00:00 UTC).

Syntax:

const date = new Date(milliseconds);

Parameters:

  • milliseconds: A numeric value representing the number of milliseconds since the Unix Epoch (January 1, 1970).

Example:

1. Creating a Date from Milliseconds

const date = new Date(0); console.log(date);

Output:

Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)

Explanation:

  • The 0 milliseconds represent the exact Unix Epoch (January 1, 1970, 00:00:00 UTC).

2. Using a Positive Number of Milliseconds

const date = new Date(86400000); // 86,400,000 milliseconds = 1 day console.log(date);

Output:

Fri Jan 02 1970 00:00:00 GMT+0000 (Coordinated Universal Time)

Explanation:

  • 86400000 milliseconds represent 1 day after the Unix Epoch, which corresponds to January 2, 1970.

3. Using a Negative Number of Milliseconds

const date = new Date(-86400000); // -86,400,000 milliseconds = 1 day before Epoch console.log(date);

Output:

Wed Dec 31 1969 00:00:00 GMT+0000 (Coordinated Universal Time)

Explanation:

  • -86400000 milliseconds represent 1 day before the Unix Epoch, resulting in December 31, 1969.

4. Using a Large Number of Milliseconds

const date = new Date(1700000000000); // Far in the future console.log(date);

Output:

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

Explanation:

  • 1700000000000 milliseconds represent November 4, 2023, at 22:46:40 UTC.

Summary:

  • new Date(milliseconds) creates a Date object based on the number of milliseconds since January 1, 1970.
  • Positive values represent dates after the Unix Epoch, while negative values represent dates before.
  • You can use this method to calculate dates in the past or future relative to the Epoch by adding or subtracting milliseconds.