Valip
Valip

Reputation: 4610

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

Upvotes: 0

Views: 101

Answers (2)

havr
havr

Reputation: 51

var d = new Date();
d.setDate(d.getDate()-30);
d = d.toISOString().slice(0,10);

Upvotes: 0

epascarello
epascarello

Reputation: 207501

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

Upvotes: 5

Related Questions