如何在 Material UI KeyboardDatePicker 中选择日期后获取明确的时间
How to get explicit time after selecting a date in Material UI KeyboardDatePicker
当我在日历上选择日期时,它 return 向我提供了所需的日期,但带有当前时间。这是在七点钟随机选择一天后的输出示例:'Tue Dec 01 2020 19:28:00 GMT+0200 (Eastern European Standard Time)'。我希望它 return 我 00:00:00,就像我自己将日期写入输入而不在日历上选择它时所做的那样。
这是一个日期选择器的代码片段:
<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',
}}
/>
Material 日期选择器将始终放置浏览器时区的当前时秒,我对此有很多问题,但您始终可以这样做
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',
}}
/>
)
}
这将使使用 UTC 的日期成为一天的开始,您也可以使用 setHours,但那个将使用您的浏览器时区,这可能因用户位置而异。
如果您的要求需要特定时区(这就是我最终所做的),我还建议使用 Luxon 库和 luxon utils 而不是 date-fns。
当我在日历上选择日期时,它 return 向我提供了所需的日期,但带有当前时间。这是在七点钟随机选择一天后的输出示例:'Tue Dec 01 2020 19:28:00 GMT+0200 (Eastern European Standard Time)'。我希望它 return 我 00:00:00,就像我自己将日期写入输入而不在日历上选择它时所做的那样。
这是一个日期选择器的代码片段:
<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',
}}
/>
Material 日期选择器将始终放置浏览器时区的当前时秒,我对此有很多问题,但您始终可以这样做
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',
}}
/>
)
}
这将使使用 UTC 的日期成为一天的开始,您也可以使用 setHours,但那个将使用您的浏览器时区,这可能因用户位置而异。
如果您的要求需要特定时区(这就是我最终所做的),我还建议使用 Luxon 库和 luxon utils 而不是 date-fns。