user3442470
user3442470

Reputation: 439

Moment is not adding day

I have the following javascript:

const to = moment(item.to);
const toNextDay = to.add(1, 'days');

item.to is a string that has the following format:

"2020-06-30T00:00:00"

But is not adding the next day, that would be "2020-07-01T00:00:00"

This is the Function:

  private getCurrentRecord(records: ConfigRecord[]) {
    let result: string = null;
    for (let index = records.length - 1; index >= 0; index--) {
      const item = records[index];

      if (item.from && item.to) {

        const from = moment(item.from);
        const to = moment(item.to).add(1, 'days');
        const today = moment();
        console.log(today.format());
        if (from <= today && today < to) {
          result = item.value;
          break;
        }
      }
    }
    return result;
  }

Upvotes: 4

Views: 2271

Answers (3)

Vivek Patel
Vivek Patel

Reputation: 1057

Try this one:

const to = moment("2020-06-30T00:00:00");
const toNextDay = moment(to.add(1, 'days').toDate());

As moment is modifying the original moment object, either use toString() or toDate() to get the modified date.

const to = moment("2020-06-30T00:00:00");
const toNextDay = moment(to.add(1, 'days').toDate());
console.log('In local time => ', toNextDay.toString());

const toUTC = moment.utc("2020-06-30T00:00:00");
const toNextDayUTC = moment.utc(toUTC.add(1, 'days').toDate());
console.log('In UTC => ', toNextDayUTC.toString());
<script src="https://momentjs.com/downloads/moment.min.js"></script>

Upvotes: 3

joy08
joy08

Reputation: 9652

Try the following. Parse the string using moment's second argument then use add() to add the specified number of days

var input = "2020-06-30T00:00:00";
let addDay = moment(input, "YYYY-MM-DD hh:mm:ss").add(1, "days");
console.log(addDay.format("YYYY-MM-DDTHH:mm:ss"));
<script src="https://momentjs.com/downloads/moment.js"></script>

Upvotes: 1

Al Hill
Al Hill

Reputation: 479

Check the rest of the code because this part is correct

const to = moment("2020-06-30T00:00:00")

//undefined

to.format()

//"2020-06-30T00:00:00+02:00"

const nextDay = to.add(1, "day")

//undefined

nextDay.format()

//"2020-07-01T00:00:00+02:00"

to.format()

//"2020-07-01T00:00:00+02:00"

A little warning, Moment.add() mutates the moment so after to.add(1, "day") to and nextDay are the same date, 2020-07-01. Use to.clone().add(1, "day") if you don't want to lose the original moment

Upvotes: 1

Related Questions