Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How do I subtract one week from this date in JavaScript?
To subtract one week (7 days) from a date in JavaScript, use the setDate() method combined with getDate() to modify the date object directly.
Syntax
var newDate = new Date(currentDate.setDate(currentDate.getDate() - 7));
Method 1: Modifying Current Date
First, get the current date, then subtract 7 days using setDate():
var currentDate = new Date();
console.log("The current Date = " + currentDate);
var before7Daysdate = new Date(currentDate.setDate(currentDate.getDate() - 7));
console.log("The One week ago date = " + before7Daysdate);
The current Date = Tue Jul 14 2020 19:12:43 GMT+0530 (India Standard Time) The One week ago date = Tue Jul 07 2020 19:12:43 GMT+0530 (India Standard Time)
Method 2: Without Modifying Original Date
To keep the original date unchanged, create a new Date object:
var currentDate = new Date();
console.log("Original date = " + currentDate);
var oneWeekAgo = new Date(currentDate);
oneWeekAgo.setDate(currentDate.getDate() - 7);
console.log("One week ago = " + oneWeekAgo);
console.log("Original unchanged = " + currentDate);
Original date = Tue Jul 14 2020 19:12:43 GMT+0530 (India Standard Time) One week ago = Tue Jul 07 2020 19:12:43 GMT+0530 (India Standard Time) Original unchanged = Tue Jul 14 2020 19:12:43 GMT+0530 (India Standard Time)
Method 3: Using Milliseconds
Alternatively, subtract 7 days worth of milliseconds:
var currentDate = new Date();
var millisecondsInWeek = 7 * 24 * 60 * 60 * 1000; // 7 days in milliseconds
var oneWeekAgo = new Date(currentDate.getTime() - millisecondsInWeek);
console.log("Current date = " + currentDate);
console.log("One week ago = " + oneWeekAgo);
Current date = Tue Jul 14 2020 19:12:43 GMT+0530 (India Standard Time) One week ago = Tue Jul 07 2020 19:12:43 GMT+0530 (India Standard Time)
Comparison
| Method | Modifies Original | Complexity | Best For |
|---|---|---|---|
setDate() direct |
Yes | Simple | When original date not needed |
setDate() with copy |
No | Simple | Preserving original date |
| Milliseconds subtraction | No | Medium | Precise time calculations |
Conclusion
Use setDate(getDate() - 7) for simplicity. Create a new Date object first if you need to preserve the original date. The milliseconds approach offers more precision for complex date calculations.
Advertisements
