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:
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
Output:
Explanation:
- Initially,
date
contains the current date and time. - After calling
date.setTime(1000000)
, the date is set to1000000
milliseconds after January 1, 1970, which is00:16:40 UTC
on January 1, 1970.
Example 2: Using Negative Milliseconds
You can pass negative values to represent dates before January 1, 1970.
Output:
Explanation:
- A negative value of
-1000000
milliseconds sets the date toWed 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.
Output:
Explanation:
- The milliseconds value
1735689600000
corresponds toDecember 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
.
Output:
Explanation:
- Initially, the
date
object contains the current date and time. - After calling
date.setTime(0)
, the date is reset toJanuary 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.