JavaScript Date setTime()
Syntax & Examples


Date.setTime() method

The setTime() method of the Date object in JavaScript sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. Use negative numbers for times prior.


Syntax of Date.setTime()

The syntax of Date.setTime() method is:

setTime(timeValue)

This setTime() method of Date sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. Use negative numbers for times prior.

Parameters

ParameterOptional/RequiredDescription

Return Type

Date.setTime() returns value of type Number.



✐ Examples

1 Using setTime() to set a specific time

In JavaScript, we can use the setTime() method to set a Date object to a specific time represented by milliseconds since January 1, 1970, 00:00:00 UTC.

For example,

  1. We create a new Date object date representing January 1, 2021.
  2. We use the setTime() method to set the date to 86400000 milliseconds (1 day) after January 1, 1970, 00:00:00 UTC.
  3. The modified date 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-01T00:00:00Z');
date.setTime(86400000);
console.log(date);

Output

1970-01-02T00:00:00.000Z

2 Using setTime() with the current date

In JavaScript, we can use the setTime() method to set a Date object to the current time in milliseconds since January 1, 1970, 00:00:00 UTC.

For example,

  1. We create a new Date object now representing the current date and time.
  2. We use the setTime() method to set the date to the current time in milliseconds since January 1, 1970, 00:00:00 UTC.
  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.setTime(Date.now());
console.log(now);

Output

The output will vary based on the current date and time.

3 Using setTime() with a negative time value

In JavaScript, we can use the setTime() method to set a Date object to a time before January 1, 1970, 00:00:00 UTC by using a negative time value.

For example,

  1. We create a new Date object pastDate representing January 1, 2000.
  2. We use the setTime() method to set the date to -86400000 milliseconds (1 day) before January 1, 1970, 00:00:00 UTC.
  3. The modified date 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('2000-01-01T00:00:00Z');
pastDate.setTime(-86400000);
console.log(pastDate);

Output

1969-12-31T00:00:00.000Z

Summary

In this JavaScript tutorial, we learned about setTime() method of Date: the syntax and few working examples with output and detailed explanation for each example.