Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
  }
like image 405
user3442470 Avatar asked Oct 22 '25 07:10

user3442470


2 Answers

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>
like image 127
Vivek Patel Avatar answered Oct 23 '25 21:10

Vivek Patel


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

like image 44
Al Hill Avatar answered Oct 23 '25 19:10

Al Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!