Skip to content
Advertisement

Moment object won’t increment by days when cloned and used with DateTimePicker

I have the following code:

  function localDateHandler(momentObj) {


      let start = momentObj.clone();
      let update = start.add(10, 'days');

      console.log(update);    // Does not change, SHOULD be ten days more than momentObj
      console.log(momentObj);

}

I am using the following React component to change the date:

 <DateTimePicker value={eventDate} onChange={localDateHandler}/> 

The info for the component is here: https://material-ui-pickers.dev/

When I change the date the date is not incremented by the number of days listed in the first block of code (I explain more in the comments)

Thank you!

Advertisement

Answer

I reproduce and this works with not any problem. What you have seen maybe caused by one of these case:

  • You might have briefly looked at _i of moment object, this might be the initial object (which could derive from momentObj.clone()), instead, you should look _d instead (moment object internal properties doc)

    The most commonly viewed internal property is the _d property that holds the JavaScript Date that Moment wrappers.

  • You might not have use the right version of peer dependency for moment adapter (installation guide)

    Important: For material-ui-pickers v3 use v1.x version of @date-io adapters.

Codesandbox for demonstration, you should open the log to check

Edit frosty-mcnulty-wu5s1

enter image description here

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement