Skip to content Skip to sidebar Skip to footer

Material Ui Datepicker Showing Wrong Date

The displayed date in Material UI Pickers is 1 day behind the selected date: I selected 25th, the value in formik is 25th but the value displayed on the form is 24th. '@date-io/

Solution 1:

I've faced the same problem

After all, I added a parseISO method on my date, you need to specify the timezone of the component.

// import parseISOimport { parseISO } from'date-fns'; 

On value (property which is date)

<KeyboardDatePickerformat={DateFormatEnum.DayMonthYearPtBr}label="Date"value={parseISO(salesPage.dateAt)}onChange={handleDateAtOnChange}
/>

On change

import { format } from'date-fns';
import { convertToLocalTime } from'date-fns-timezone';


exportconstDEFAULT_DATE_FORMAT = 'yyyy-MM-dd';

/**
 * Format a date to a string
 *
 * @paramdate
 */exportconstformatDate = (date) => {
  if (!date) returnnewDate().toLocaleString();

  // Get the timezone from browser using native methodsconst timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  const dateTmp = Date.parse(date.toLocaleString());

  const localDate = convertToLocalTime(dateTmp, {
    timeZone: timezone,
  });

  returnformat(localDate, DEFAULT_DATE_FORMAT);
};

consthandleDateAtOnChange = (event) => {
  formatDate(event.target.value)
}


Solution 2:

its because datepicker takes input date-time in UTC ISOformat Solution - Convert UTC to local to ISO format

because server only accepts ISO date-time so I converted UTC to local timezone and sent it to server in ISO format

declare this somewhere

functionconvertUTCDateToLocalDate(date) {
    var newDate = newDate(date.getTime() - date.getTimezoneOffset()*60*1000);
    return newDate;   
}

and do this where you need local datetime in ISO format convertUTCDateToLocalDate(date).toISOString()

Post a Comment for "Material Ui Datepicker Showing Wrong Date"