gpt4 book ai didi

javascript - 如何在react-flatpickr中自动设置当前时间?

转载 作者:行者123 更新时间:2023-11-28 03:28:59 28 4
gpt4 key购买 nike

我正在使用 react-flatpickr 库作为我的项目的日期选择器。使用该库的问题是,如果我选择任何日期,它总是将时间视为 00:00:00。由于这种行为,当来自不同时区的用户保存日期时,它会产生问题。

当用户选择日期时,有什么方法可以传递用户的本地时间吗?

我还研究了enableTime: true,它也允许选择时间。此选项也无法设置当前时间。

这是我的代码。

const options = {
enableTime: false,
dateFormat: 'd-m-Y'
};

<Flatpickr
placeholder="Select date"
ref={datepickerRef}
options={options}
value={props.field.value ? props.field.value : ''}
onChange={(date) => {
let selectedDate = new Date(date[0]);
props.form.setFieldTouched(props.field.name);
props.form.setFieldValue(props.field.name, selectedDate);
}}

/>

下午 06:41,

输出:2019 年 10 月 11 日星期五 00:00:00 GMT+0530(印度标准时间)

预期输出:2019 年 10 月 11 日星期五 18:41:00 GMT+0530(印度标准时间)

最佳答案

由于该库不支持该格式,我们可以使用 setHours(hours,min,sec) native 方法将自定义时间设置为所选日期。

获取当前时间并将这些值设置为您选择的日期

<Flatpickr
placeholder="Select date"
ref={datepickerRef}
options={options}
value={props.field.value ? props.field.value : ''}
onChange={(date) => {
let selectedDate = date[0];
let currentDate = new Date();
let selectedDateWithCurrentTime = new Date(
selectedDate.setHours(currentDate.getHours(), currentDate.getMinutes(), currentDate.getSeconds())
);
console.log('selectedDateWithCurrentTime',selectedDateWithCurrentTime); // Fri Oct 11 2019 19:47:53 GMT+0530 (India Standard Time)
props.form.setFieldTouched(props.field.name);
props.form.setFieldValue(props.field.name, selectedDateWithCurrentTime.toISOString());
}}
/>

在此处检查示例 https://codesandbox.io/s/flatpicker-with-current-time-txdsx

关于javascript - 如何在react-flatpickr中自动设置当前时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58342053/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com