The JavaScript setTime function is used to set the time by adding or subtracting user-specified milliseconds to a default date, January 1, 1970, 00:00:00. Here, you have to specify the time in Milliseconds.
The syntax of the setTime function is:
Date.setTime(Milliseconds)
Parameter: It accepts an integer value representing the time in milliseconds. This number is added to the default date.
Return Value: The setTime() method adds or subtracts the given number of milliseconds from the default January 1, 1970, 00:00:00 date and time.
JavaScript setTime example
In the following example, we use the setTime function to add 20000000 milliseconds to the default 1970-01-01 midnight.
let dt = new Date();
console.log(dt);
dt.setTime(20000000);
console.log(dt);
Mon Jun 15 2026 11:11:29 GMT+0530 (India Standard Time)
Thu Jan 01 1970 11:03:20 GMT+0530 (India Standard Time)
Example 2: In this code, we will use a negative sign. It means the setTime() method subtracts 500000000 milliseconds from 1970-01-01 midnight.
let dt = new Date();
console.log(dt);
dt.setTime(-500000000);
console.log(dt);
Mon Jun 15 2026 11:35:32 GMT+0530 (India Standard Time)
Fri Dec 26 1969 10:36:40 GMT+0530 (India Standard Time)
Example 3: In this JavaScript set Time function example, we set the Time of a custom date to 2000 milliseconds.
let dt = new Date("January 1, 2017 23:45:22");
console.log(dt);
dt.setTime(2000);
console.log(dt);
Sun Jan 01 2017 23:45:22 GMT+0530 (India Standard Time)
Thu Jan 01 1970 05:30:02 GMT+0530 (India Standard Time)
Example 4: Here, we use the JavaScript setTime() function to update the date value from an existing date and time. To do so, we need the getTime() to get the milliseconds from an existing date. Next, use those milliseconds as the setTime() function parameter value.
const dt = new Date("2025-10-01");
console.log(dt);
const n = new Date();
n.setTime(dt.getTime());
console.log(n);
Wed Oct 01 2025 05:30:00 GMT+0530 (India Standard Time)
Wed Oct 01 2025 05:30:00 GMT+0530 (India Standard Time)
Why does setTime() return milliseconds instead of a date?
By default, the setTime() updates the original date by adding or subtracting milliseconds. However, if we assign the result to a new variable, it returns the milliseconds value of the updated date.
const dt = new Date();
let t = dt.setTime(100000000);
console.log(t);
console.log(dt);
100000000
Fri Jan 02 1970 09:16:40 GMT+0530 (India Standard Time)