Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/date-fns": "^1.3.13",
  "date-fns": "^2.9.0",
import DateFnsUtils from '@date-io/date-fns';
import { MuiPickersUtilsProvider, DatePicker } from '@material-ui/pickers';
import { format, addDays } from 'date-fns';

<MuiPickersUtilsProvider utils={DateFnsUtils}>
    <FastField
       as={DatePicker}
       variant="inline"
       disableToolbar
       name="startTime"
       format="PPP"
       onChange={date => {
         console.log(format(date, 'yyyy-MM-dd'));
         setFieldValue('startTime', format(date, 'yyyy-MM-dd'));
       }}
       value={values.startTime}
   />
</MuiPickersUtilsProvider>

enter image description here

like image 263
Batman Avatar asked Feb 24 '20 18:02

Batman


2 Answers

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 parseISO
import { parseISO } from 'date-fns'; 

On value (property which is date)

<KeyboardDatePicker
  format={'dd/MM/yyyy'}
  label="Date"
  value={parseISO(salesPage.dateAt)}
  onChange={handleDateAtOnChange}
/>

On change


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


export const DEFAULT_DATE_FORMAT = 'yyyy-MM-dd';

/**
 * Format a date to a string
 *
 * @param date
 */
export const formatDate = (date) => {
  if (!date) return new Date().toLocaleString();

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

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

  return format(localDate, DEFAULT_DATE_FORMAT);
};

const handleDateAtOnChange = (event) => {
  formatDate(event.target.value)
}


like image 150
João Mantovani Avatar answered Oct 02 '22 20:10

João Mantovani


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

function convertUTCDateToLocalDate(date) {
    var newDate = new Date(date.getTime() - date.getTimezoneOffset()*60*1000);
    return newDate;   
}

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

like image 20
Suvesh Avatar answered Oct 02 '22 21:10

Suvesh