How to Subtract One Year From a Date in JavaScript
JavaScript is an object-oriented scripting language that is commonly used in web development due to its ability to dynamically render webpages. The use of objects in JavaScript can lead to simplification of many commands by grouping multiple related pieces of information together. One example of this simplification is subtracting one year from the current date, something that can be handled quite easily in JavaScript using objects.
Instructions
-
-
1
Designate a variable called "date" to store the current date:
var date = new Date('25 Dec 2010');
-
2
Output the result to the console to ensure the above step is correct:
console.log(date);
-
-
3
In the "month" date type, within the "date" object, subtract 12 from the current number. This will give you a date 12 months in the past, stored as the current date:
date.setMonth(date.getMonth() -- 12);
-
4
Again, output the result. The new date should be exactly 12 months prior to the current date (in the example used above, the new date would be "25 Dec 2009"):
console.log(date);
-
1
Tips & Warnings
Make sure you follow proper syntax, such as ending lines with a semicolon.
References
Resources
- Photo Credit Hemera Technologies/AbleStock.com/Getty Images
Comments
-
basicfix
Dec 06, 2010
This article is incorrect: There is syntax error in the only line that matters! To subtract 12 months, use: date.setMonth(date.getMonth() - 12); Or better yet, simply subtract a year (!): date.setYear(date.getFullYear() - 1); Also, using: console.log(date); assumes you're using a tool that knows what to do with that (e.g. Firebug). The author should point this out. If you're simply running in a browser (likely, given that this is a "beginner question"), something like: window.alert(date); is much more generic.