<input type="datetime-local">

datetime-local 类型的 <input> 元素创建输入控件,使用户可以轻松输入日期和时间,包括年、月、日以及以小时和分钟为单位的时间。

¥<input> elements of type datetime-local create input controls that let the user easily enter both a date and a time, including the year, month, and day as well as the time in hours and minutes.

Try it

一般来说,该控件的 UI 根据浏览器的不同而有所不同。在不支持的浏览器中,这些控件会优雅地降级为简单的 <input type="text"> 控件。

¥The control's UI varies in general from browser to browser. In browsers with no support, these degrade gracefully to simple <input type="text"> controls.

该控件旨在表示本地日期和时间,而不一定是用户的本地日期和时间。换句话说,输入允许年、月、日、小时和分钟的任何有效组合,即使这样的组合在用户的本地时区中无效(例如夏令时向前转换中的一小时) 差距)。

¥The control is intended to represent a local date and time, not necessarily the user's local date and time. In other words, the input allows any valid combination of year, month, day, hour, and minute—even if such a combination is invalid in the user's local time zone (such as the one hour within a daylight saving time spring-forward transition gap).

¥Value

表示输入中输入的日期值的字符串。该输入类型使用的日期和时间值的格式在 本地日期和时间字符串 中描述。

¥A string representing the value of the date entered into the input. The format of the date and time value used by this input type is described in Local date and time strings.

你可以通过在 value 属性中包含日期和时间来设置输入的默认值,如下所示:

¥You can set a default value for the input by including a date and time inside the value attribute, like so:

html
<label for="party">Enter a date and time for your party booking:</label>
<input
  id="party"
  type="datetime-local"
  name="partydate"
  value="2017-06-01T08:30" />

需要注意的一点是,显示的日期和时间格式与实际的 value 不同;显示的日期和时间根据操作系统报告的用户区域设置进行格式化,而日期/时间 value 始终采用 YYYY-MM-DDThh:mm 格式。例如,当上面的值提交到服务器时,它将看起来像 partydate=2024-06-01T08:30

¥One thing to note is that the displayed date and time formats differ from the actual value; the displayed date and time are formatted according to the user's locale as reported by their operating system, whereas the date/time value is always formatted YYYY-MM-DDThh:mm. When the above value is submitted to the server, for example, it will look like partydate=2024-06-01T08:30.

注意:另请记住,如果通过 HTTP GET 提交此类数据,则需要对冒号字符进行转义以将其包含在 URL 参数中,例如 partydate=2024-06-01T08%3A30。请参阅 encodeURI() 了解执行此操作的一种方法。

¥Note: Also bear in mind that if such data is submitted via HTTP GET, the colon character will need to be escaped for inclusion in the URL parameters, e.g. partydate=2024-06-01T08%3A30. See encodeURI() for one way to do this.

你还可以使用 HTMLInputElement value 属性在 JavaScript 中获取和设置日期值,例如:

¥You can also get and set the date value in JavaScript using the HTMLInputElement value property, for example:

js
const dateControl = document.querySelector('input[type="datetime-local"]');
dateControl.value = "2017-06-01T08:30";

附加属性

¥Additional attributes

除了所有 <input> 元素共有的属性外,datetime-local 输入还提供以下属性。

¥In addition to the attributes common to all <input> elements, datetime-local inputs offer the following attributes.

max

最晚接受的日期和时间。如果输入到元素中的 value 晚于该时间戳,则该元素失败 约束验证。如果 max 属性的值不是遵循格式 YYYY-MM-DDThh:mm 的有效字符串,则该元素没有最大值。

¥The latest date and time to accept. If the value entered into the element is later than this timestamp, the element fails constraint validation. If the value of the max attribute isn't a valid string that follows the format YYYY-MM-DDThh:mm, then the element has no maximum value.

该值指定的日期字符串必须晚于或等于 min 属性指定的日期字符串。

¥This value must specify a date string later than or equal to the one specified by the min attribute.

min

最早接受的日期和时间;早于此的时间戳将导致元素失败 约束验证。如果 min 属性的值不是遵循格式 YYYY-MM-DDThh:mm 的有效字符串,则该元素没有最小值。

¥The earliest date and time to accept; timestamps earlier than this will cause the element to fail constraint validation. If the value of the min attribute isn't a valid string that follows the format YYYY-MM-DDThh:mm, then the element has no minimum value.

该值指定的日期字符串必须早于或等于 max 属性指定的日期字符串。

¥This value must specify a date string earlier than or equal to the one specified by the max attribute.

step

step 属性是一个数字,指定值必须遵守的粒度,或者是特殊值 any,如下所述。只有等于步进基础的值(如果指定则为 min,否则为 value,如果未提供则为适当的默认值)才有效。

¥The step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. Only values which are equal to the basis for stepping (min if specified, value otherwise, and an appropriate default value if neither of those is provided) are valid.

字符串值 any 意味着不暗示任何步进,并且允许任何值(除非其他约束,例如 minmax)。

¥A string value of any means that no stepping is implied, and any value is allowed (barring other constraints, such as min and max).

注意:当用户输入的数据不符合步进配置时,user agent 可能会四舍五入到最接近的有效值,当有两个同样接近的选项时,优先选择正方向的数字。

¥Note: When the data entered by the user doesn't adhere to the stepping configuration, the user agent may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options.

对于 datetime-local 输入,step 的值以秒为单位给出,缩放因子为 1000(因为基础数值以毫秒为单位)。step 的默认值为 60,表示 60 秒(或 1 分钟,或 60000 毫秒)。

¥For datetime-local inputs, the value of step is given in seconds, with a scaling factor of 1000 (since the underlying numeric value is in milliseconds). The default value of step is 60, indicating 60 seconds (or 1 minute, or 60,000 milliseconds).

目前,还不清楚当与 datetime-local 输入一起使用时 any 的值对于 step 意味着什么。一旦确定该信息,我们将立即更新。

¥At this time, it's unclear what a value of any means for step when used with datetime-local inputs. This will be updated as soon as that information is determined.

使用日期时间本地输入

¥Using datetime-local inputs

日期/时间输入方便开发者;它们提供了一个简单的用户界面来选择日期和时间,并且无论用户的区域设置如何,它们都会标准化发送到服务器的数据格式。但是,考虑你的用户很重要。不要要求你的用户输入应用运行不需要的数据。

¥Date/time inputs are convenient for the developer; they provide an easy UI for choosing dates and times, and they normalize the data format sent to the server, regardless of the user's locale. However, it is important to consider your users. Don't require your users to enter data that is not needed for your app to function.

控制输入大小

¥Controlling input size

<input type="datetime-local"> 不支持表单控件大小调整属性,例如 size。你必须求助于 CSS 来自定义这些元素的大小。

¥<input type="datetime-local"> doesn't support form control sizing attributes such as size. You'll have to resort to CSS for customizing the sizes of these elements.

设置时区

¥Setting timezones

datetime-local 输入类型不提供的一件事是设置日期/时间控件的时区和/或区域设置的方法。这在 datetime 输入类型中可用,但该类型现已过时,已从规范中删除。删除此功能的主要原因是浏览器中缺乏实现以及对用户界面/体验的担忧。仅使用一个(或多个)控件来设置日期/时间,然后在单独的控件中处理区域设置会更容易。

¥One thing the datetime-local input type doesn't provide is a way to set the time zone and/or locale of the date/time control. This was available in the datetime input type, but this type is now obsolete, having been removed from the spec. The main reasons why this was removed are a lack of implementation in browsers and concerns over the user interface/experience. It is easier to just have a control (or controls) for setting the date/time and then deal with the locale in a separate control.

例如,如果你正在创建一个用户可能已经登录且已设置区域设置的系统,则可以在 hidden 输入类型中提供时区。例如:

¥For example, if you are creating a system where the user is likely to already be logged in, with their locale already set, you could provide the timezone in a hidden input type. For example:

html
<input type="hidden" id="timezone" name="timezone" value="-08:00" />

另一方面,如果你需要允许用户输入时区以及日期/时间输入,则可以使用 <select> 元素,使用户能够通过从以下位置中选择特定位置来设置正确的时区: 位置集:

¥On the other hand, if you were required to allow the user to enter a time zone along with a date/time input, you could have a <select> element to enable the user to set the right time zone by choosing a particular location from among a set of locations:

html
<select name="timezone" id="timezone">
  <option value="Pacific/Kwajalein">Eniwetok, Kwajalein</option>
  <option value="Pacific/Midway">Midway Island, Samoa</option>
  <option value="Pacific/Honolulu">Hawaii</option>
  <option value="Pacific/Marquesas">Taiohae</option>
  <!-- and so on -->
</select>

在任何一种情况下,日期/时间和时区值都将作为单独的数据点提交到服务器,然后你需要将它们适当地存储在服务器端的数据库中。

¥In either case, the date/time and time zone values would be submitted to the server as separate data points, and then you'd need to store them appropriately in the database on the server-side.

验证

¥Validation

默认情况下,<input type="datetime-local"> 不对输入的值应用任何验证。UI 实现通常不允许你输入任何非日期/时间的内容(这很有帮助),但用户可能仍然不填写任何值并提交,或者输入无效的日期和/或时间(例如 32 日) 四月)。

¥By default, <input type="datetime-local"> does not apply any validation to entered values. The UI implementations generally don't let you enter anything that isn't a date/time — which is helpful — but a user might still fill in no value and submit, or enter an invalid date and/or time (e.g. the 32nd of April).

你可以使用 minmax 来限制可用日期(请参阅 设置最大和最小日期),并且可以使用 required 属性强制填写日期/时间。因此,如果你尝试提交超出设置范围的日期或空日期字段,支持的浏览器将显示错误。

¥You can use min and max to restrict the available dates (see Setting maximum and minimum dates), and you can use the required attribute to make filling in the date/time mandatory. As a result, supporting browsers will display an error if you try to submit a date that is outside the set bounds or an empty date field.

让我们看一个例子;在这里,我们设置了最小和最大日期/时间值,并将该字段设为必填:

¥Let's look at an example; here we've set minimum and maximum date/time values, and also made the field required:

html
<form>
  <div>
    <label for="party">
      Choose your preferred party date and time (required, June 1st 8.30am to
      June 30th 4.30pm):
    </label>
    <input
      id="party"
      type="datetime-local"
      name="partydate"
      min="2017-06-01T08:30"
      max="2017-06-30T16:30"
      required />
    <span class="validity"></span>
  </div>
  <div>
    <input type="submit" value="Book party!" />
  </div>
</form>

如果你尝试提交日期不完整(或日期超出设定范围)的表单,浏览器会显示错误。现在尝试使用示例:

¥If you try to submit the form with an incomplete date (or with a date outside the set bounds), the browser displays an error. Try playing with the example now:

这是上面示例中使用的 CSS。这里我们利用 :valid:invalid CSS 属性根据当前值是否有效来设置输入样式。我们将图标放在输入旁边的 <span> 上。

¥Here's the CSS used in the above example. Here we make use of the :valid and :invalid CSS properties to style the input based on whether the current value is valid. We put the icons on a <span> next to the input.

css
div {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

label {
  display: inline-block;
  width: 300px;
}

input:invalid + span::after {
  content: "✖";
  padding-left: 5px;
}

input:valid + span::after {
  content: "✓";
  padding-left: 5px;
}

警告:HTML 表单验证不能替代确保输入数据格式正确的脚本。对于某人来说,对 HTML 进行调整以绕过验证或完全删除它太容易了。其他人也有可能完全绕过你的 HTML 并将数据直接提交到你的服务器。如果你的服务器端代码无法验证其接收到的数据,则在提交格式不正确的数据(或数据太大、类型错误等)时可能会出现问题。

¥Warning: HTML form validation is not a substitute for scripts that ensure that the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, problems can arise when improperly-formatted data is submitted (or data that is too large, is of the wrong type, and so forth).

注意:对于 datetime-local 输入,日期值始终标准化为 YYYY-MM-DDThh:mm 格式。

¥Note: With a datetime-local input, the date value is always normalized to the format YYYY-MM-DDThh:mm.

示例

¥Examples

datetime-local 的基本用法

¥Basic uses of datetime-local

<input type="datetime-local"> 最简单的使用涉及基本的 <input><label> 元素组合,如下所示:

¥The simplest use of <input type="datetime-local"> involves a basic <input> and <label> element combination, as seen below:

html
<form>
  <label for="party">Enter a date and time for your party booking:</label>
  <input id="party" type="datetime-local" name="partydate" />
</form>

设置最大和最小日期和时间

¥Setting maximum and minimum dates and times

你可以使用 minmax 属性来限制用户可以选择的日期/时间。在以下示例中,我们将最小日期时间设置为 2024-06-01T08:30,最大日期时间设置为 2024-06-30T16:30

¥You can use the min and max attributes to restrict the dates/times that can be chosen by the user. In the following example, we are setting a minimum datetime of 2024-06-01T08:30 and a maximum datetime of 2024-06-30T16:30:

html
<form>
  <label for="party">Enter a date and time for your party booking:</label>
  <input
    id="party"
    type="datetime-local"
    name="partydate"
    min="2024-06-01T08:30"
    max="2024-06-30T16:30" />
</form>

只能选择 2024 年 6 月的日期。根据你使用的浏览器,指定值之外的时间可能无法选择。在其他浏览器中,可以选择无效的日期和时间,但会匹配 :invalid:out-of-range,而会失败 validation

¥Only days in June 2024 can be selected. Depending on what browser you are using, times outside the specified values might not be selectable. In other browsers, invalid dates and times are selectable but will match :invalid and :out-of-range and will fail validation.

在某些浏览器(Chrome 和 Edge)中,只有日期值的 "days" 部分是可编辑的,六月以外的日期无法滚动。在其他版本(Safari)中,日期选择器将显示允许任何日期,但选择日期时该值将被限制在有效范围内。

¥In some browsers (Chrome and Edge), only the "days" part of the date value will be editable, and dates outside June can't be scrolled. In others (Safari), the date picker will appear to allow any date, but the value will be clamped to the valid range when a date is selected.

有效范围包括 minmax 值之间的所有时间;一天中的时间仅限制在范围内的第一个和最后一个日期。

¥The valid range included all times between the min and max values; the time of day is only constrained on the first and last dates in the range.

注意:你应该能够使用 step 属性来改变每次日期增加时跳跃的天数(例如,也许你只想选择星期六)。然而,在撰写本文时,这似乎在任何实现中都没有有效地发挥作用。

¥Note: You should be able to use the step attribute to vary the number of days jumped each time the date is incremented (e.g. maybe you only want to make Saturdays selectable). However, this does not seem to work effectively in any implementation at the time of writing.

技术总结

¥Technical summary

表示日期和时间(本地时区)的字符串,或者为空。
活动 changeinput
支持的通用属性 autocompletelistreadonlystep
IDL 属性 list, value, valueAsNumber.
DOM 接口

HTMLInputElement

方法 select(), stepDown(), stepUp()
隐式 ARIA 角色 no corresponding role

规范

Specification
HTML Standard
# local-date-and-time-state-(type=datetime-local)

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看