JavaScript Date.UTC()

Posted by

Understanding the JavaScript Date.UTC() Method

The Date.UTC() method in JavaScript is used to return the number of milliseconds in a Date object since January 1, 1970, 00:00:00 UTC. It takes up to seven arguments for the year, month, day, hour, minute, second, and millisecond to create a Date object. The UTC version of the Date object is used to prevent any timezone issues.

Syntax

The syntax for the Date.UTC() method is as follows:

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

Date.UTC(year, month[, day[, hour[, minute[, second[, millisecond]]]]])

[/dm_code_snippet]

Parameters

The Date.UTC() method takes the following parameters:

  • year: An integer representing the year.
  • month: An integer between 0 (January) and 11 (December).
  • day: An integer between 1 and 31.
  • hour: An integer between 0 (midnight) and 23 (11 pm).
  • minute: An integer between 0 and 59.
  • second: An integer between 0 and 59.
  • millisecond: An integer between 0 and 999.

Return Value

The Date.UTC() method returns the number of milliseconds between the specified date and midnight of January 1, 1970, in the UTC timezone.

Examples

Let’s look at some examples of the Date.UTC() 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”]

let date = Date.UTC(2020, 6, 7);
console.log(date); // 1591584000000

let date = Date.UTC(2020, 6, 7, 12, 0, 0, 500);
console.log(date); // 1591616000500

[/dm_code_snippet]

In the first example, we create a Date object with the UTC method, using only the year, month, and day parameters. The returned value is the number of milliseconds from midnight of January 1, 1970, to 12:00 AM of the specified date. In the second example, we use all the parameters to create a Date object, and the returned value is the number of milliseconds from midnight of January 1, 1970, to 12:00 PM of the specified date.

Conclusion

The Date.UTC() method in JavaScript is used to return the number of milliseconds in a Date object since January 1, 1970, 00:00:00 UTC. It takes up to seven arguments for the year, month, day, hour, minute, second, and millisecond to create a Date object.