You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为datetime-local输入框设置默认00:00小时?(Chrome v73)

Fixing the Invalid Date Issue with datetime-local in Chrome 73

Hey there, let's work through this problem you're having with the datetime-local input! Chrome 73 does have that annoying quirk where the date picker only lets you select the date portion, leaving the time part empty by default—and that's exactly why your JS is throwing invalid date errors. Here's how to fix it:

1. Set a Static Default Value Directly in HTML

The datetime-local input only accepts values in the YYYY-MM-DDTHH:mm format (this is a strict browser requirement we can't get around). To set a default of midnight for a specific date, just hardcode the value like this:

<input id="creation-from-date" type="datetime-local" value="2024-05-20T00:00"/>

Replace 2024-05-20 with your desired date, keeping the T00:00 suffix for midnight.

2. Dynamically Set the Current Date at Midnight with JavaScript

If you want the default to be the current date at 00:00, use JS to generate the correctly formatted string and assign it to the input. Here's a clean, reliable way to do it:

// Helper function to add leading zeros to single-digit numbers
function padZero(num) {
  return num < 10 ? `0${num}` : num;
}

// Get today's date
const today = new Date();
// Format to YYYY-MM-DDTHH:mm (HH:mm = 00:00)
const defaultDateTime = `${today.getFullYear()}-${padZero(today.getMonth() + 1)}-${padZero(today.getDate())}T00:00`;

// Assign to the input
document.getElementById('creation-from-date').value = defaultDateTime;

We use padZero here to ensure months/days are always two digits (e.g., 05 instead of 5), which is mandatory for the format to be recognized as valid.

3. Add a Safety Net for User Input

Even with a default value, users might accidentally delete the time part. Add a change event listener to auto-repair the value if needed:

const dateInput = document.getElementById('creation-from-date');

dateInput.addEventListener('change', (e) => {
  const inputValue = e.target.value;
  // If only the date part is present (length 10 = YYYY-MM-DD), append midnight time
  if (inputValue.length === 10) {
    e.target.value = `${inputValue}T00:00`;
  }
});

This ensures the input always has a complete datetime string, so your JS won't hit invalid date errors when parsing it.

Why This Works

Chrome 73's datetime-local picker preserves the time portion when you change the date—so once you set the initial 00:00, modifying the date will keep the time at midnight. This eliminates the empty time segment that was causing your invalid date issue.

内容的提问来源于stack exchange,提问作者Majestic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:20:33