gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
how do I subtract 1 day from a javascript date?
- User
how do I subtract 1 day from a javascript date?
- Assistant
To subtract 1 day from a JavaScript
Dateobject, you can use thesetDate()andgetDate()methods. Here's a simple way to do it:const date = new Date(); // current date date.setDate(date.getDate() - 1); // subtract 1 day console.log(date);Explanation:
date.getDate()returns the day of the month (1 to 31).- Subtracting 1 decreases the day by one.
date.setDate()updates the day of the month, automatically adjusting the month and year if necessary (e.g., from March 1st to February 28th).
This approach correctly handles month boundaries and leap years.
If you'd like a reusable function, here’s one:
function subtractDays(date, days) { const result = new Date(date); result.setDate(result.getDate() - days); return result; } const today = new Date(); const yesterday = subtractDays(today, 1); console.log(yesterday);This way you can subtract any number of days.