Does anybody know of a simple way of taking a date (e.g. Today) and going back X days, X months and X years?
I have tried that:
var date = new Date(); $("#searchDateFrom").val((date.getMonth() -1 ) + '/' + (date.getDate() - 6) + '/' + (date.getFullYear() - 1));
But I got a negative date, for example today the output was:
3/-3/2015
Any advise?
Thanks.
function subtractYears(numOfYears, date = new Date()) { date. setFullYear(date. getFullYear() - numOfYears); return date; } // 👇️ subtract 1 year from current Date const result = subtractYears(1); // 👇️ Subtract 2 years from another Date const date = new Date('2022-04-26'); // 👇️ Sun Apr 26 2020 console.
Subtract dates using getTime() method And that's how you can subtract dates in JavaScript.
Therefore, you can add or subtract days as easy as adding or minus the number of days in Excel. 1. Select a blank cell you will place the calculating result, type the formula =A2+10, and press the Enter key. Note: For subtracting 10 days from the date, please use this formula =A2–10.
Show activity on this post. let yesterday=new Date(new Date(). getTime() - (1 * 24 * 60 * 60 * 1000)); let last3days=new Date(new Date(). getTime() - (3 * 24 * 60 * 60 * 1000));
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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With