Bipin
Bipin

Reputation: 3

time is changing while we use react-datepicker

i have selected 12:00 Pm in datepicker and i also console log it .... it shows Thu Jul 09 2020 12:00:00 GMT+0530 (India Standard Time) which is right time. but when i click on save then it sends wrong time (2020-07-09T06:30:00.454Z). It sends 5 and half hour less to the time which user selected. It should send (2020-07-09T012:00:00.454Z)----Expected Behaviour i dont know what is the issue and how to fixx this my code

 <DatePicker
        selected={new Date(value)}
        onChange={(e) => setFieldValue(field.name, e)}
        className={classes.datePicker}
        todayButton="Today"
        {...rest}
      />

I need to pass exact same time which user has selected . I think this issue occurs due to timezone or utc etc . so please help

Upvotes: 0

Views: 4941

Answers (1)

Tim Gerhard
Tim Gerhard

Reputation: 3607

This is a common problem with javascript. I usually write a "fix timezone offset" function ald call this function before I send my code to the backend:

export const fixTimezoneOffset = (date: Date) : string => {
  if(!date) return "";
  return new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON();
}

And you call it like this: fixTimezoneOffset(my_date)

Disclaimer: fixTimezoneOffset returns a string which will automatically be computed into a datetime object in your backend. Call fixTimezoneOffset only once and not multiple times!!

Upvotes: 6

Related Questions