【问题标题】:how to set future time in material-ui <textfield type="datetime-local" />如何在 material-ui <textfield type="datetime-local" /> 中设置未来时间
【发布时间】:2021-12-15 07:35:30
【问题描述】:

我想将默认时间设置为比当前时间晚 4 小时,所以如果是 2021 年 10 月 31 日凌晨 3:00,则默认时间应显示为 2021 年 10 月 31 日凌晨 4:00 在 2021 年 10 月 31 日晚上 10:00 这样的时间里,它应该显示 2021 年 11 月 1 日凌晨 2:00

我尝试将当前时间加到 4,但它会破坏夜间时间。


const currentDate = new Date();

  const dateTime = `${currentDate.getFullYear()}-${currentDate.getMonth() + 1}-${currentDate.getDate()}T${
    currentDate.getHours() + 3
  }:${currentDate.getMinutes()}`;


<TextField
 id="datetime-local"
 type="datetime-local"
 defaultValue={`${dateTime}`}
 InputLabelProps={{
     shrink: true,
     }}
 InputProps={{ inputProps: { min: `${dateTime}` } }}
 onChange={handleChange}
 />
 </div>

【问题讨论】:

    标签: reactjs datetime datepicker material-ui


    【解决方案1】:

    您可以使用来自 Date 对象的 setHoursgetHours 方法。

    const currentDate = new Date();
    const fourHoursLater = new Date(
      currentDate.setHours(currentDate.getHours() + 4)
    );
    

    codesandbox

    【讨论】:

      【解决方案2】:

      在这种情况下,您应该添加之前的小时数,即使小时数高于 24 小时,javascript Date 也会处理并返回正确的时间。

      const currentDate = new Date();
      currentDate.setHours(currentDate.getHours() + 4);
      

      现在您可以使用 Date 对象了。

      【讨论】:

        猜你喜欢
        • 2019-07-09
        • 1970-01-01
        • 1970-01-01
        • 2021-02-19
        • 2019-05-20
        • 2012-09-16
        • 2021-04-18
        • 2022-12-14
        • 2023-02-16
        相关资源
        最近更新 更多