I have array with some dates:

periods[i].start
periods[i].ende

Initially I populate start date. Then I want to calculate end date, like this:

periods[i].ende = periods[i+1].start - 1 day

This works:

periods[i].ende = periods[i+1].start;

But how to do: -1 day?

Thanks!

EDIT: It's not duplicate of this. Method setDate works for a single variable like YOURDATE, but not for something like PERIODS[i].ENDE. Difference - maybe one is reference, other is value. I used this code:

function finalizePeriods() {
  var tempDay;
  for(var i=0; i<periods.length - 1; i++) {
    tempDay = new Date(periods[i+1].start);
    tempDay.setDate(tempDay.getDate() - 1);
    periods[i].ende = tempDay;
  }
}

MBottens, thanks again!

有帮助吗?

解决方案

Heres one way of doing it. This will set each end date except for the last one. Since there is not a date to calculate it from.

JS Fiddle: http://jsfiddle.net/FGt4B/1/

var periods = [{start: "5/1/2014"}, {start: "5/8/2014"}, {start: "5/15/2014"}],
    period, nextPeriod, tempDay

for ( var i = 0, _len = periods.length; i < _len; i++ ) {
    period = periods[i]
    nextPeriod = periods[i+1]

    if ( nextPeriod ) {
        tempDay = new Date(nextPeriod.start)
        tempDay.setDate(tempDay.getDate() -1)
        period.end = tempDay.toLocaleDateString()
    }
}

console.log(periods)

其他提示

A suggestion may be to use moment.js library. Then just

moment.subtract('days', 1);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top