I need to add 1 day to a date variable in TypeScript. May I know how can I add a day to a date field in TypeScript.
const date = new Date(); date. setDate(date. getDate() + 1); // ✅ 1 Day added console.
To add 1 day to the current date with JavaScript, we can use the setDate method. to get the current day with getDate , then add 1 to it. And then we pass that as the argument of setDate to add 1 to the current date .
let yesterday=new Date(new Date(). getTime() - (1 * 24 * 60 * 60 * 1000)); let last3days=new Date(new Date(). getTime() - (3 * 24 * 60 * 60 * 1000));
This is just regular JavaScript, no need for TypeScript.
yourDate = new Date(yourDate.getTime() + (1000 * 60 * 60 * 24));
1000 milliseconds in a second * 60 seconds in a minute * 60 minutes in an hour * 24 hours.
Additionally you could increment the date:
yourDate.setDate(yourDate.getDate() + 1);
The neat thing about setDate
is that if your date is out-of-range for the month, it will still correctly update the date (January 32 -> February 1).
See more documentation on setDate on MDN.
addDays(date: Date, days: number): Date {
date.setDate(date.getDate() + days);
return date;
}
In your case days = 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With