The setUTCDate method in JavaScript is utilized to establish the day of a Date object based on Coordinated Universal Time (UTC). When the specified day value exceeds the limits of the month, the setUTCDate method will automatically modify the Date object to accommodate this adjustment.
Syntax
The method setUTCDate can be described using this syntax:
dateObj.setUTCDate(dayValue)
Parameter
dayValue - It represents the day of the month.
JavaScript Date setUTCDate method example
In this section, we will explore the setUTCDate function by examining several illustrative examples.
Example 1
Let us examine an illustration that demonstrates how to specify the day for the current date.
<script>
var date=new Date();
document.writeln("Today?s day : "+date.getUTCDate()+"<br>");
date.setUTCDate(15);
document.writeln("Updated day : "+date.getUTCDate());
</script>
Output:
Today's day : 9
Updated day : 15
Example 2
Let's examine an illustration to modify the day component of a specified date.
<script>
var date = new Date("August 15, 1947 20:22:10");
date.setUTCDate(20);
document.writeln("Updated day : "+date.getUTCDate());
</script>
Output:
Updated day : 20
Example 3
In this instance, we will supply a day value that exceeds the total number of days available in the month. As a result, the setUTCDate method will modify the Date object to reflect the subsequent month.
<script>
var date = new Date("August 15, 1947 20:22:10");
document.writeln("Previous date : "+date.getUTCDate()+"/"+(date.getUTCMonth()+1)+"/"+date.getUTCFullYear()+"<br>");
date.setUTCDate(32);
document.writeln("Updated date : "+date.getUTCDate()+"/"+(date.getUTCMonth()+1)+"/"+date.getUTCFullYear());
</script>
Output:
Previous date : 15/8/1947
Updated date : 1/9/1947
Example 4
In this scenario, we will supply a day value that is lower than the number of days available in the specified month. As a result, the setUTCDate method will modify the Date object to reflect the previous month.
<script>
var date = new Date("August 15, 1947 20:22:10");
document.writeln("Previous date : "+date.getUTCDate()+"/"+(date.getUTCMonth()+1)+"/"+date.getUTCFullYear()+"<br>");
date.setUTCDate(0);
document.writeln("Updated date : "+date.getUTCDate()+"/"+(date.getUTCMonth()+1)+"/"+date.getUTCFullYear());
</script>
Output:
Previous date : 15/8/1947
Updated date : 31/7/1947