Gintoki
Gintoki

Reputation: 117

Subtracting a Day from a Full Date

I need to subtract 1 day from a string value of a date I have, for example when I subtract a day from 2017/01/01 instead of getting 2016/12/31 I end up getting a value of 2017/0/31.

Below is the code I'm working on:

                var inputDate = "2017/01/01";
                var splitClndr = inputDate.value.split("/");
                var clndrDate = new Date(splitClndr[0], splitClndr[1], splitClndr[2]);
                clndrDate.setDate(clndrDate.getDate() - 1);
                var nd = new Date(clndrDate);
                var dd = nd.getDate();
                var mm = nd.getMonth();
                var y = nd.getFullYear();
                var newFormattedDate = y + '/'+ mm + '/'+ dd;
                operatorDate.value = newFormattedDate;

The value I get in the variable newFromattedDate is 2017/0/31, how can I make the result of subtracting a day to 2016/12/31 instead?

Upvotes: 0

Views: 213

Answers (4)

Rahul
Rahul

Reputation: 18577

Try this,

   var inputDate = "2017/01/01";
   var splitClndr = inputDate.split("/");
   var clndrDate = new Date(splitClndr[0], splitClndr[1] - 1, splitClndr[2]);
   var past_time = clndrDate.getTime() - 1000 * 60 * 60 * 24 * 1; // last 1 will be day
   clndrDate.setTime(past_time);
   console.log(clndrDate);

Working jsfilddle.

Upvotes: 0

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14624

You can use setDate method to subtract the number of days you want.

var inputDate = "2017/01/01"; 
var newDate = new Date(inputDate); 
newDate.setDate(newDate.getDate() - 1);
console.log(newDate);

Upvotes: 0

Fernando Gonzalez
Fernando Gonzalez

Reputation: 148

You can just substract directly from the date:

var d = new Date('2017/01/01');
d.setDate(d.getDate() - 1);
var newDateString = d.toLocaleDateString();
console.log(newDateString);

Upvotes: 0

David Hedlund
David Hedlund

Reputation: 129812

Months in javascript are zero-based, so 0 is January:

new Date(2017, 1, 1) >> Wed Feb 01 2017

You need to compensate for this, both when creating your clndrDate and when concatenating your string.

new Date(splitClndr[0], splitClndr[1]-1, splitClndr[2])

...

var mm = nd.getMonth()+1;

Upvotes: 1

Related Questions