首页 > 解决方案 > 设置默认日期和时间

问题描述

我正在使用 Material-UI,这是他们的示例代码。

但是我需要 defaultValue 是今天的当前日期和时间;我该怎么办?

<TextField
    id="datetime-local"
    label="Next appointment"
    type="datetime-local"
    defaultValue="2017-05-24T10:30"
    className={classes.textField}
    InputLabelProps={{'
      shrink: true,
    }}
  />

我曾尝试使用类似的东西,但是问题是如果月份和日期是 1-9,那么单个数字而不是两位数意味着它不会设置。

const currentdate = new Date(); 

  const datenow = currentdate.getFullYear() + "-"
                  + (currentdate.getMonth()+1)  + "-" 
                  + currentdate.getDay() + "T"  
                  + currentdate.getHours() + ":"  
                  + currentdate.getMinutes();
  

标签: node.jsreactjs

解决方案


你可以做这样的事情。

  const d = new Date(); 
  const year = (d.getFullYear()).toString();
  const month = ((d.getMonth()) + 101).toString().slice(-2);
  const date = ((d.getDate()) + 100).toString().slice(-2);

  const hours = ((d.getHours()) + 100).toString().slice(-2);
  const mins = ((d.getMinutes()) + 100).toString().slice(-2);

  const datenow = `${year}-${month}-${date}T${hours}:${mins}`;

推荐阅读