Pavel Valeriu Pavel Valeriu - 4 months ago 19
Javascript Question

Get date with prior 30 days to current date

I try to subtract 30 days to current date and I always receive a negative number to day value. The most important thing is the format of the returned date, that must be

YYYY-MM-DD
.

I know that there are similar questions like this but I couldn't find a solution.

This is what I've done so far..

var date = new Date();

var dd = date.getDate()-30;
var mm = date.getMonth()+1;

var yyyy = date.getFullYear();
if(dd<10){
dd='0'+dd
}
if(mm<10){
mm='0'+mm
}
var dateTo = yyyy+'-'+mm+'-'+dd;


The above code will return 2016-07- -10 for today date instead of 2016-07-21

Answer

Because you are subtracting from a number that has NO connection to the date object. Changing it does nothing but change the number. You need to subtract the days from the date itself.

var today = new Date();
var past30 = new Date();
past30.setDate(today.getDate()-30);
console.log(past30);

Comments