Javascript: Subtracting Days/Hours/Minutes from a Date

There will be many cases where you need to subtract a number of days/hours/minutes/seconds from a given date object. The following examples will demonstrate how to do that in Javascript.
In the first example, we’re just subtracting days from a date. It is both simple to understand and common in practice. Here’s the code:
const subtractDays = (date, days) => {
const result = new Date(date);
result.setDate(result.getDate() - days);
return result;
}
console.log(subtractDays(new Date('2022-12-30 19:40:39'), 10));
Output:
Tue Dec 20 2022 19:40:39 GMT+0000 (Greenwich Mean Time)
The second example is more complete because it allows you to list the number of days, hours, minutes, and seconds to subtract. Here’s the code:
const subtractTime = (date, days, hours, minutes, seconds) => {
const result = new Date(date);
result.setDate(result.getDate() - days);
result.setHours(result.getHours() - hours);
result.setMinutes(result.getMinutes() - minutes);
result.setSeconds(result.getSeconds() - seconds);
return result;
}
console.log(subtractTime(new Date('2022-12-30 19:40:39'), 30, 5, 30, 10));
Output:
Wed Nov 30 2022 14:10:29 GMT+0000 (Greenwich Mean Time)
In both examples, we declared functions to increase reusability. This isn’t a must-do but I think it’s elegant. Javascript is fun and useful in tech life. Keep learning to hone your skills:
- 2 Ways to Format Currency in Javascript
- Javascript Object: Find the Key(s) of a given Value
- Javascript: How to Reverse an Integer
- Javascript: Looping through Keys/Values of an Object
- VS Code & Javascript/TypeScript: Place Curly Braces on New Line
You can also check out our Javascript category page, TypeScript category page, Node.js category page, and React category page for the latest tutorials and examples.