• JavaScript Video Tutorials

JavaScript Date setMilliseconds() Method



The JavaScript Date.setMilliseconds() method is used to set the "milliseconds" of a date object. The milliseconds value can range from 0 to 999. It returns the number of milliseconds between the date object's time and midnight of January 1, 1970, after the milliseconds component has been set.

If the provided date object is "invalid", this method returns Not a Number (NaN) as result. This method modifies the milliseconds component of a date object without changing other date components.

Syntax

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

setMilliseconds(millisecondsValue);

Parameters

This method accepts only one parameter. The same is described below −

  • millisecondsValue − An integer representing the milliseconds (0 to 999).
    • If -1 is provided, it will result in the last millisecond of the previous second.
    • If 1000 is provided, it will result in the first millisecond of the next second.

Return Value

This method does not return a new date object. Instead, it modifies the existing Date object by setting its milliseconds component to the specified value.

Example 1

In the following example, we are using the JavaScript Date setMilliseconds() method to set the "milliseconds" of the current Date to 500 −

<html>
<body>
<script>
   const myDate = new Date();
   myDate.setMilliseconds(500);

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

Output

If we execute the above program, the milliseconds will be set to 500.

Example 2

Here, we are adding 300000 milliseconds to the current date −

<html>
<body>
<script>
   const currentDate = new Date();
   const millisecondsToAdd = 300000; // Add 5 minutes (300000 milliseconds)

   currentDate.setMilliseconds(currentDate.getMilliseconds() + millisecondsToAdd);

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

Output

The above program will add 5 minutes to the current date.

Example 3

If we provide "-1" for millisecondsValue, this method will gives the last millisecond of the previous second −

<html>
<body>
<script>
   const myDate = new Date();
   myDate.setMilliseconds(-1);

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

Output

This method returns "999" as last millisecond of the previous second.

Example 4

If we provide "1000" for millisecondsValue, this method will gives the first millisecond of the next second −

<html>
<body>
<script>
   const myDate = new Date();
   myDate.setMilliseconds(1000);

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

Output

This method returns "0" as first millisecond of the next second.

Advertisements