Date.setMilliseconds() function in JavaScript


The Date object is a data type built into the JavaScript language. Date objects are created with the new Date( ) as shown below.

Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time.

The setMilliseconds() function of the date object accepts an integer representing the milliseconds and modifies/replaces the value of the milliseconds in the current date with it.

Syntax

Its Syntax is as follows

dateObj.setMilliseconds();

Example

 Live Demo

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date('september 26, 89 12:4:25:96');
      dateObj.setMilliseconds(225);
      document.write(dateObj.getMilliseconds());
   </script>
</body>
</html>

Output

225

Example

Though you do not mention the milliseconds of the day while creating the date object, You can still set it using the setMilliSeconds() function.

 Live Demo

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date('september 26, 89 12:4:25');
      dateObj.setMilliseconds(225);
      document.write(dateObj.getMilliseconds());
   </script>
</body>
</html>

Output

225

Example

In the same way, though you do not pass any value to the constructor while creating the date object still you can set the milliseconds using this function and the month, date, year and, other values remain same as in the current date (and time).

 Live Demo

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date();
      dateObj.setMilliseconds(55);
      document.write(dateObj.toString());
      document.write("<br>");
      document.write(dateObj.getMilliseconds());
   </script>
</body>
</html>

Output

Thu Oct 18 2018 21:55:39 GMT+0530 (India Standard Time)
55

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 25-Jun-2020

34 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements