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

ParameterOptional/RequiredDescription

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,

  1. We create a new Date object date representing January 15, 2021, at 10:20:30.500.
  2. We use the setMilliseconds() method to set the milliseconds to 750.
  3. The modified date and time is stored in the date object.
  4. We log the modified date to the console using console.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,

  1. We create a new Date object now representing the current date and time.
  2. We use the setMilliseconds() method to set the milliseconds to 123.
  3. The modified date and time is stored in the now object.
  4. We log the modified now to the console using console.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,

  1. We create a new Date object pastDate representing July 4, 1776, at 12:00:00.000.
  2. We use the setMilliseconds() method to set the milliseconds to 456.
  3. The modified date and time is stored in the pastDate object.
  4. We log the modified pastDate to the console using console.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.