Subtract days, months, years from a date in JavaScript
Solution 1:
You are simply reducing the values from a number. So substracting 6 from 3 (date) will return -3 only.
You need to individually add/remove unit of time in date object
var date = new Date();
date.setDate( date.getDate() - 6 );
date.setFullYear( date.getFullYear() - 1 );
$("#searchDateFrom").val((date.getMonth() ) + '/' + (date.getDate()) + '/' + (date.getFullYear()));
Solution 2:
As others have said you're subtracting from the numeric values returned from methods like date.getDate()
, you need to reset those values on your date variable. I've created a method below that will do this for you. It creates a date using new Date()
which will initialize with the current date, then sets the date, month, and year according to the values passed in. For example, if you want to go back 6 days then pass in -6 like so var newdate = createDate(-6,0,0)
. If you don't want to set a value pass in a zero (or you could set default values). The method will return the new date for you (tested in Chrome and Firefox).
function createDate(days, months, years) {
var date = new Date();
date.setDate(date.getDate() + days);
date.setMonth(date.getMonth() + months);
date.setFullYear(date.getFullYear() + years);
return date;
}
Solution 3:
2021 Update:
MomentJS has been replaced/improved with LuxonJS, a much more up-to-date and newer version. You can find it here: https://moment.github.io/luxon/#/
I'll leave the old post for now, since it could sitll help others.
Old post:
I'd recommend using the MomentJS libraries. They make all interactions with Dates a lot simpler.
If you use Moment, your code would be as simple as this:
var today = moment();
var nextMonth = today.add('month', 1);
// note that both variables `today` and `nextMonth` refer to
// the next month at this point, because `add` mutates in-place
You can find MomentJS here: http://momentjs.com/
UPDATE:
In JavaScript, the Date.getDate() function returns the current day of the month from 1-31. You are subtracting 6 from this number, and it is currently the 3rd of the month. This brings the value to -3.