Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

reactjs - 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',
        }}
      />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...