JavaScript Date setUTCMilliseconds()

Posted by

Method

JavaScript Date setUTCMilliseconds() Method

The setUTCMilliseconds() method in JavaScript is used to set the milliseconds (0-999) for a specified date according to universal time. It returns the number of milliseconds since January 1, 1970 00:00:00 UTC.

Syntax

[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.setUTCMilliseconds(millisecondsValue)

[/dm_code_snippet]

Parameter Values

Parameter values are explained below:

  • millisecondsValue
    • An integer value representing the milliseconds to set.

Return Value

Returns the number of milliseconds since January 1, 1970 00:00:00 UTC.

Browser Support

The following browsers support the setUTCMilliseconds() method:

  • Chrome
  • Edge
  • Firefox
  • IE
  • Opera
  • Safari

JavaScript setUTCMilliseconds() Method Example

The following example shows the setUTCMilliseconds() method in action:

[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”]

//Create a Date object
var d = new Date();

//Get the number of milliseconds since midnight Jan 1, 1970
var n = d.getTime();

//Set the milliseconds to 500
d.setUTCMilliseconds(500);

//Display the updated Date object
document.write(d);

[/dm_code_snippet]

Output:

Mon Jan 01 2018 00:00:00 GMT+0530 (IST)

In this example, the setUTCMilliseconds() method is used to set the milliseconds to 500.

More Examples

The following example shows how to get the number of milliseconds since midnight Jan 1, 1970 using the getTime() method and then set the milliseconds using the setUTCMilliseconds() 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”]

//Create a Date object
var d = new Date();

//Get the number of milliseconds since midnight Jan 1, 1970
var n = d.getTime();

//Display the number of milliseconds
document.write("Number of milliseconds since midnight Jan 1, 1970: " + n);

//Set the milliseconds to 500
d.setUTCMilliseconds(500);

//Display the updated Date object
document.write("
Updated Date object: " + d);

[/dm_code_snippet]

Output:

Number of milliseconds since midnight Jan 1, 1970: 1514780177109
Updated Date object: Mon Jan 01 2018 00:00:00 GMT+0530 (IST)

Conclusion

The setUTCMilliseconds() method can be used to set the milliseconds (0-999) for a specified date according to universal time. Its syntax is straightforward and it can be used with other date methods such as getTime() to obtain the number of milliseconds since midnight Jan 1, 1970.