Method
JavaScript Date setTime() Method
The JavaScript Date setTime() method is used to set or change the time of a Date object. It accepts a parameter of the number of milliseconds since midnight of January 1, 1970, and sets the Date object accordingly. This method can be used to reset the time of a Date object, allowing you to quickly set the time to a specific value.
Syntax
The syntax for the setTime() method is as follows:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
dateObj.setTime(milliseconds);
[/dm_code_snippet]
Parameters
The setTime() method takes a single parameter, milliseconds, which is the number of milliseconds since midnight of January 1, 1970.
Return Value
The setTime() method returns the number of milliseconds since midnight of January 1, 1970 for the specified date.
Examples
The following example shows how to use the setTime() method:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
var date = new Date();
// Set the time to 8:30pm
date.setTime(14 * 60 * 60 * 1000);
// Display the time
document.write(date);
[/dm_code_snippet]
The output of the code above will be:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
Tue Jan 01 2019 20:30:00 GMT+0000 (GMT Standard Time)
[/dm_code_snippet]
The following example shows how to reset the time of a Date object to a specific value:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
var date = new Date();
// Reset the time to 8:30pm
date.setTime(14 * 60 * 60 * 1000);
// Display the time
document.write(date);
[/dm_code_snippet]
The output of the code above will be:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
Tue Jan 01 2019 20:30:00 GMT+0000 (GMT Standard Time)
[/dm_code_snippet]
Browser Support
The setTime() method is supported in all major browsers, including Internet Explorer, Firefox, Chrome, and Safari.