Search code examples
typescriptreact-reduxutcreact-datepicker

Save selected date and not utc date in react redux


I tried following this link and find a solution with the help of this question.

This question had a part of the information that I need but it did not provide me with an answer. This almost had what I wanted but redux does not let me pass the output date in the state.

I am writing a react application using redux (typescript v. ^3.8) and have a dateTimePicker component that uses the "react-datepicker" npm package version : v.2.15. I select a value from the picker let's say 07/07/2020, but when I save it in a state with a reducer,

the action.payload is of type Tue Jul 07 2020 00:00:00 GMT+0300 (Eastern European Summer Time)

but inside the state I now have 2020-07-06T21:00:00.000Z.

My understanding is the property that the date is being saved, is of type date but the format "YYYY-MM-DDTHH:mm:ss.SSSZ" is an ISOstring() in utc.

How can I pass only the selected value (07/07/2020) in the state, without taking into account local/utc date and timezone? I am aiming to have just this 2020-07-07T00:00:00.000Z

In my reducer how should I manipulate the date to have the above result? My code snippet is this:

export const changeGeneralFormDateReducer = (
  state: IState,
  action: IAction<Date>
): IState =>
  produce(state, (draftState: IState) => {   
    draftState.generalForm.Date = action.payload;    
  });

Solution

  • use something like this

    draftState.generalForm.Date = new Date(
        Date.UTC(
          action.payload.getFullYear(),
          action.payload.getMonth(),
          action.payload.getDate()
        )
      );