簡體   English   中英

如何在 material-ui 中為當前日期和時間的文本字段類型 datetime-local 設置默認值?

[英]how can I set the default value to the textfield type datetime-local in material-ui for the current date and time?

我希望我設置的文本字段默認值是當前日期和時間,為此我做了這個

const currentDate = new Date();
const dateTime = `${currentDate.getFullYear()}-${currentDate.getMonth() + 1}-0${currentDate.getDate()}T${
    currentDate.getHours() + 0
  }:${currentDate.getMinutes()}`;
<TextField
   id="datetime-local"
   type="datetime-local"
   defaultValue={`${dateTime}`}
   InputLabelProps={{
     shrink: true,
     }}
   InputProps={{ inputProps: { min: `${dateTime}` } }}
   onChange={handleChange}
 />

直到今天,當日期為 11 月 1 日的個位數時,它一直工作正常,當小時和分鍾也是個位數時,它甚至也會中斷,因為 material-ui 需要格式為“yyyy-MM-ddThh”的默認值:毫米”。

有誰知道如何解決它?

謝謝!

嘗試在數字小於 10 時添加前綴“0”以避免格式不匹配問題。

 const addingPrefix = (data) => data <9 ? `0${data}`: data
    const currentDate = new Date();
    const dateTime = `${currentDate.getFullYear()}-${addingPrefix(currentDate.getMonth()+1)}-${addingPrefix(currentDate.getDate())}T${
            addingPrefix(currentDate.getHours()) + 0
          }:${addingPrefix(currentDate.getMinutes())}`;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM