Computer >> Computer tutorials >  >> Programming >> Javascript

Date.setUTCDate() function in JavaScript


The Date object is a data type built into the JavaScript language. Date objects are created with the new Date( ) as shown below.

Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time.

The setUTCDate() function of the date object accepts an integer representing the date (day of the month) and replaces the value of the current date with it, according to the universal time.

Syntax

Its Syntax is as follows

dateObj.setUTCDate(19);

Example

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date('September 26, 89 12:4:25:96');
      document.write("Current date: "+dateObj.toUTCString());
      document.write("<br>");
      dateObj.setUTCDate(30);
      document.write("Modified date: "+dateObj.toUTCString());
   </script>
</body>
</html>

Output

Current date: Tue, 26 Sep 1989 06:34:25 GMT
Modified date: Sat, 30 Sep 1989 06:34:25 GMT

Example

Though you do not mention the date of the month while creating the date object, You can still set it using the setUTCDate() function.

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date('September, 1989 00:4:00');
      dateObj.setUTCDate(2);
      document.write("<br>");
      document.write(dateObj.getUTCDate());
   </script>
</body>
</html>

Output

2

Example

In the same way, though you do not pass any value to the constructor while creating the date object still you can set the UTC Date using this function and the moth and year value remain same as the current date.

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date();
      dateObj.setUTCDate(2);
      document.write("<br>");
      document.write("UTC month: "+dateObj.getUTCMonth());
      document.write("<br>");
      document.write("UTC date: "+dateObj.getUTCDate());
      document.write("<br>");
      document.write("UTC fullyear: "+dateObj.getUTCFullYear());
   </script>
</body>
</html>

Output

UTC month: 9
UTC date: 2
UTC full year: 2018