JavaScript Date setMilliseconds()
Syntax & Examples
Date.setMilliseconds() method
The setMilliseconds() method of the Date object in JavaScript sets the milliseconds for a specified date according to local time.
Syntax of Date.setMilliseconds()
The syntax of Date.setMilliseconds() method is:
setMilliseconds(millisecondsValue)
This setMilliseconds() method of Date sets the milliseconds for a specified date according to local time.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
|
Return Type
Date.setMilliseconds() returns value of type Number
.
✐ Examples
1 Using setMilliseconds() to set milliseconds for a date
In JavaScript, we can use the setMilliseconds()
method to set the milliseconds for a Date object.
For example,
- We create a new Date object
date
representing January 15, 2021, at 10:20:30.500. - We use the
setMilliseconds()
method to set the milliseconds to 750. - The modified date and time is stored in the
date
object. - We log the modified
date
to the console usingconsole.log()
method.
JavaScript Program
const date = new Date('2021-01-15T10:20:30.500Z');
date.setMilliseconds(750);
console.log(date);
Output
2021-01-15T10:20:30.750Z
2 Using setMilliseconds() with the current date
In JavaScript, we can use the setMilliseconds()
method to set the milliseconds for the current date.
For example,
- We create a new Date object
now
representing the current date and time. - We use the
setMilliseconds()
method to set the milliseconds to 123. - The modified date and time is stored in the
now
object. - We log the modified
now
to the console usingconsole.log()
method.
JavaScript Program
const now = new Date();
now.setMilliseconds(123);
console.log(now);
Output
The output will vary based on the current date and time, with the milliseconds set to 123.
3 Using setMilliseconds() with a specific date in the past
In JavaScript, we can use the setMilliseconds()
method to set the milliseconds for a specific date in the past.
For example,
- We create a new Date object
pastDate
representing July 4, 1776, at 12:00:00.000. - We use the
setMilliseconds()
method to set the milliseconds to 456. - The modified date and time is stored in the
pastDate
object. - We log the modified
pastDate
to the console usingconsole.log()
method.
JavaScript Program
const pastDate = new Date('1776-07-04T12:00:00.000Z');
pastDate.setMilliseconds(456);
console.log(pastDate);
Output
1776-07-04T12:00:00.456Z
Summary
In this JavaScript tutorial, we learned about setMilliseconds() method of Date: the syntax and few working examples with output and detailed explanation for each example.