. Advertisement .
. Advertisement .
getDate method gets the day of the Date. You can subtract the number of days with this method. To set the date, call the
Check out the tutorial to look at the code
const date = new Date("05/28/2021"); // 28th May 2021 console.log(date.getDate()); // 28
const date = new Date("05/28/2021"); // 28th May 2021 // Set the day to 10th date.setDate(10); console.log(date); // 10th May 2021
With the combination of these two methods, days can be subtracted from the date
const date = new Date("05/28/2021"); // 28th May 2021 // Subtract 7 days from the Date object date.setDate(date.getDate() - 7); console.log(date); // 21st May 2021
setDate() adjusts the month and year of the date automatically forward and backward.
With the following code, you can subtract the days back to April.
const date = new Date("05/28/2021"); // 28th May 2021 // Subtract 35 days from the Date object date.setDate(date.getDate() - 35); console.log(date); // 23rd April 2021
Without Daylight Saving
The time is advanced if we look at the daylight saving time between March and November. In order to ignore Daylight saving time and calculate the difference, use
Date.UTC() method to convert the date. For this, you have to pass the day, month, and year to this method.
Look at the example
const date1 = new Date("05/28/2021"); // 28th May 2021 const date2 = new Date("04/17/2021"); // 17th April 2021 const date1UTC = Date.UTC( date1.getFullYear(), date1.getMonth(), date1.getDate() ); const date2UTC = Date.UTC( date2.getFullYear(), date2.getMonth(), date2.getDate() ); const difference = date1UTC - date2UTC; console.log(difference / (1000 * 60 * 60 * 24)); // 41
with this code, you can efficiently ignore the Daylight saving time while calculating.
And that’s it!
Being a beginner, it is really important to learn the basics of coding. With that note, I am hoping you get the information with this tutorial you came here for.
Feel free to drop a comment below!