JavaScript date.setTime(milliseconds) method


The date.setTime(milliseconds) method in JavaScript sets the Date object to a specific time, which is the number of milliseconds since January 1, 1970, 00:00:00 UTC (the Unix Epoch).

Syntax:

date.setTime(milliseconds);

Parameters:

  • milliseconds: An integer representing the number of milliseconds since January 1, 1970, 00:00:00 UTC.

Returns:

  • The new timestamp (the number of milliseconds since the Unix Epoch) after setting the time.

Example 1: Setting Time to a Specific Milliseconds Value

const date = new Date(); console.log('Before:', date); // Set the time to 1,000,000 milliseconds (1 second = 1000 milliseconds) date.setTime(1000000); console.log('After:', date);

Output:

Before: Tue Oct 22 2024 10:30:15 GMT+0000 (UTC) After: Thu Jan 01 1970 00:16:40 GMT+0000 (UTC)

Explanation:

  • Initially, date contains the current date and time.
  • After calling date.setTime(1000000), the date is set to 1000000 milliseconds after January 1, 1970, which is 00:16:40 UTC on January 1, 1970.

Example 2: Using Negative Milliseconds

You can pass negative values to represent dates before January 1, 1970.

const date = new Date(); date.setTime(-1000000); // Set time to -1,000,000 milliseconds (before Unix Epoch) console.log(date);

Output:

Wed Dec 31 1969 23:43:20 GMT+0000 (UTC)

Explanation:

  • A negative value of -1000000 milliseconds sets the date to Wed Dec 31 1969 23:43:20 GMT+0000 — 1,000,000 milliseconds before the Unix Epoch.

Example 3: Large Milliseconds Value (Future Date)

You can also set a large positive value to represent a future date.

const date = new Date(); date.setTime(1735689600000); // Set time to 1,735,689,600,000 milliseconds console.log(date);

Output:

Sun Dec 31 2024 00:00:00 GMT+0000 (UTC)

Explanation:

  • The milliseconds value 1735689600000 corresponds to December 31, 2024, which is a date in the future.

Example 4: Resetting a Date Object to the Unix Epoch

You can reset a Date object back to the Unix Epoch by setting the milliseconds to 0.

const date = new Date(); console.log('Before:', date); date.setTime(0); // Reset time to the Unix Epoch console.log('After:', date);

Output:

Before: Tue Oct 22 2024 10:30:15 GMT+0000 (UTC) After: Thu Jan 01 1970 00:00:00 GMT+0000 (UTC)

Explanation:

  • Initially, the date object contains the current date and time.
  • After calling date.setTime(0), the date is reset to January 1, 1970, which represents the start of the Unix Epoch.

Summary:

  • date.setTime(milliseconds) sets the date and time based on the number of milliseconds since the Unix Epoch.
  • A positive value represents dates after January 1, 1970, and negative values represent dates before.
  • This method is useful when you need to work directly with timestamps and manipulate time in terms of milliseconds.