Search code examples
reactjsuidatepicker

How to get explicit time after selecting a date in Material UI KeyboardDatePicker


When I pick the date on a calendar it returns me the needed date but with current time. Here's an example of an output after picking a random day in seven o'clock: 'Tue Dec 01 2020 19:28:00 GMT+0200 (Eastern European Standard Time)'. I want it to return me 00:00:00, as it does when I write the date into the input by myself without picking it on the calendar.

Here's a datepicker's code snippet:

<MuiPickersUtilsProvider utils={DateFnsUtils}>
      <KeyboardDatePicker
        className="search-element"
        disableToolbar
        variant="inline"
        format="dd/MM/yyyy"
        id="date-picker-inline"
        label="пошук від"
        value={firstDate}
        onChange={handleFirstDateChange}
        KeyboardButtonProps={{
          'aria-label': 'set first date',
        }}
      />

Solution

  • Material date pickers will always put the current hour seconds of your browser timezone, I have a lot of problems with that but you can always do

    import React from "react";
    
    export default function YourComponent() {
     const [firstDate, setFirstDate] = React.useState(null)
    
     const handleFirstDateChange = (date) => {
      const newDate = date;
      // Check if date is present, user can leave it as an empty field
      if (date) {
       //Set's the given date to UTC midnight (start of the day)
       newDate.setUTCHours(0,0,0,0);
      }
      // Set the date to your local state or where you are storing it
      setFirstDate(newDate)
     }
    
     return (
       <KeyboardDatePicker
        className="search-element"
        disableToolbar
        variant="inline"
        format="dd/MM/yyyy"
        id="date-picker-inline"
        label="пошук від"
        value={firstDate}
        onChange={handleFirstDateChange}
        KeyboardButtonProps={{
          'aria-label': 'set first date',
        }}
       />
     )
    }
    

    This will make the date to use the UTC start of the day, you can also use setHours but that one will use your browser timezone, which can be different depending on the user location.

    I would also suggest to use Luxon library and luxon utils instead of date-fns if your requirements need a specific timezone(this is what I ended up doing).