W3C 总是能给我整出恶心的东西,为什么把一个 Date 赋值给 <input type="datetime-local" /> 这么难?这tm是给人用的吗?🤔

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// https://dev.to/kevinluo201/set-value-of-datetime-local-input-field-3435
// getFullYear, getMonth, getDate, getHours, getMinutes all return values of local time.
const convertToDateTimeLocalString = (date) => {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");

  return `${year}-${month}-${day}T${hours}:${minutes}`;
}
const currentTime = new Date()
document.getElementById('start-time').value = convertToDateTimeLocalString(currentTime)

而如果是 Go 的话,只需要下面这样一句就可以了:

1
time.Now().Format("2006-01-02T15:04:05")
桃子的碎碎念 桃子 编辑