Pavel Valeriu Pavel Valeriu - 1 year ago 67
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


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();
var dateTo = yyyy+'-'+mm+'-'+dd;

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

Answer Source

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