Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract days, months, years from a date in JavaScript

Tags:

javascript

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.

like image 396
user3378165 Avatar asked May 03 '16 11:05

user3378165


People also ask

How do you subtract years in JavaScript?

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.

Can you subtract dates in JavaScript?

Subtract dates using getTime() method And that's how you can subtract dates in JavaScript.

How do you subtract a day from a date?

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.

How do I subtract days from a date in typescript?

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));


1 Answers

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())); 
like image 50
gurvinder372 Avatar answered Oct 13 '22 03:10

gurvinder372