如何在Material UI KeyboardDatePicker中选择日期后获得明确的时间



当我在日历上选择日期时,它会返回所需的日期,但带有当前时间。以下是在七点钟随机选择一天后的输出示例:"2020年12月1日星期二19:28:00 GMT+0200(东欧标准时间("。我希望它返回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',
}}
/>

材料日期选择器总是将当前时秒放在浏览器时区,我对此有很多问题,但你总是可以进行

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,而不是日期fns(这就是我最终所做的(。

最新更新