JavaScript Date setUTCDate()

Posted by

Method

Introduction to the JavaScript Date setUTCDate() Method

The setUTCDate() method is a part of the JavaScript Date object, which allows you to set the day of the month for a given date according to universal time. This method is useful for working with dates in different time zones, or for keeping track of dates that are based on Coordinated Universal Time (UTC).

The setUTCDate() method accepts a single argument, which is an integer representing the day of the month that should be set. The argument value must be between 1 and the maximum number of days in the given month. If the argument value is out of range, the method will return an invalid date error.

The value returned by the setUTCDate() method is the number of milliseconds since January 1, 1970 00:00:00 UTC. This value can be used to create a new Date object with an updated day of the month.

Syntax

The syntax for the setUTCDate() 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.setUTCDate(day);

[/dm_code_snippet]

Where day is an integer representing the day of the month to be set.

Example

The following example demonstrates how to use the setUTCDate() method to set the day of the month for a given date object:

[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 for January 15, 2020
let date = new Date(2020, 0, 15);

// Set the day of the month to 1
date.setUTCDate(1);

// Log the updated date
console.log(date);

[/dm_code_snippet]

In this example, the setUTCDate() method is used to set the day of the month to 1 for the given date object. The updated date object is logged to the console, which should return the following value:

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

Wed Jan 01 2020 00:00:00 GMT+0000 (Coordinated Universal Time)

[/dm_code_snippet]

As you can see, the day of the month was successfully updated to 1.

Conclusion

The JavaScript setUTCDate() method is a useful tool for working with dates in different time zones, or for keeping track of dates that are based on Coordinated Universal Time (UTC). This method accepts a single argument, which is an integer representing the day of the month that should be set, and it returns the number of milliseconds since January 1, 1970 00:00:00 UTC. This value can be used to create a new Date object with an updated day of the month.