• JavaScript Video Tutorials

JavaScript Date setTime() Method



The setTime() method is used to set the time of a Date object to the specified time, represented by the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC, also known as the Unix Epoch. This method changes the time of the Date object to the provided time without changing its year, month, and day components.

Syntax

Following is the syntax of JavaScript Date setTime() method −

setTime(timeValue);

An integer value representing the time in milliseconds since the Epoch (January 1, 1970, 00:00:00 UTC).

Return value

This method does not return a value. It modifies the original Date object in place, setting its time to the specified value.

Example 1

In the following example, we are passing 1577880000000 milliseconds (equals to 50 years) to the JavaScript Date setTime() method −

<html>
<body>
<script>
   const date = new Date();
   date.setTime(1577880000000); //incrementing 50 years since epoch

   document.write(date);
</script>
</body>
</html>

Output

As we can see the output, provided milliseconds has been added since the epoch.

Example 2

Here, we are subtracting 1577880000000 milliseconds (equals to 50 years) from January 1, 1970 −

<html>
<body>
<script>
   const date = new Date();
   date.setTime(-1577880000000); //decrementing 50 years since epoch

   document.write(date);
</script>
</body>
</html>

Output

As we can see the output, 50 years has been subtracted from epoch.

Advertisements