<input type="time">

time 类型的 <input> 元素创建输入字段,旨在让用户轻松输入时间(小时和分钟,以及可选的秒)。

¥<input> elements of type time create input fields designed to let the user easily enter a time (hours and minutes, and optionally seconds).

虽然控件的用户界面外观基于浏览器和操作系统,但功能是相同的。无论 UI 的输入格式如何,值始终是 24 小时 hh:mmhh:mm:ss 格式的时间,带有前导零。

¥While the control's user interface appearance is based on the browser and operating system, the features are the same. The value is always a 24-hour hh:mm or hh:mm:ss formatted time, with leading zeros, regardless of the UI's input format.

Try it

设置值属性

¥Setting the value attribute

你可以在创建 <input> 元素时通过在 value 属性中包含有效时间来设置输入的默认值,如下所示:

¥You can set a default value for the input by including a valid time in the value attribute when creating the <input> element, like so:

html
<label for="appt-time">Choose an appointment time: </label>
<input id="appt-time" type="time" name="appt-time" value="13:30" />

使用 JavaScript 设置值

¥Setting the value using JavaScript

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

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

js
const timeControl = document.querySelector('input[type="time"]');
timeControl.value = "15:30";

时间值格式

¥Time value format

time 输入的 value 始终采用 24 小时格式,其中包含前导零:hh:mm,无论输入格式如何,都可能根据用户的区域设置(或由用户代理)进行选择。如果时间包括秒(参见 使用步骤属性),则格式始终为 hh:mm:ss。你可以在 时间字符串 中了解有关此输入类型使用的时间值格式的更多信息。

¥The value of the time input is always in 24-hour format that includes leading zeros: hh:mm, regardless of the input format, which is likely to be selected based on the user's locale (or by the user agent). If the time includes seconds (see Using the step attribute), the format is always hh:mm:ss. You can learn more about the format of the time value used by this input type in Time strings.

在此示例中,你可以通过输入时间并查看其随后的变化来查看时间输入的值。

¥In this example, you can see the time input's value by entering a time and seeing how it changes afterward.

首先,看一下 HTML。这很简单,使用我们之前看到的标签和输入,但添加了 <p> 元素和 <span> 来显示 time 输入的值:

¥First, a look at the HTML. This is simple enough, with the label and input as we've seen before, but with the addition of a <p> element with a <span> to display the value of the time input:

html
<form>
  <label for="startTime">Start time: </label>
  <input type="time" id="startTime" />
  <p>
    Value of the <code>time</code> input:
    <code> "<span id="value">n/a</span>"</code>.
  </p>
</form>

JavaScript 代码将代码添加到时间输入以监视 input 事件,每次输入元素的内容发生更改时都会触发该事件。发生这种情况时,<span> 的内容将替换为输入元素的新值。

¥The JavaScript code adds code to the time input to watch for the input event, which is triggered every time the contents of an input element change. When this happens, the contents of the <span> are replaced with the new value of the input element.

js
const startTime = document.getElementById("startTime");
const valueSpan = document.getElementById("value");

startTime.addEventListener(
  "input",
  () => {
    valueSpan.innerText = startTime.value;
  },
  false,
);

当提交包含 time 输入的表单时,该值会在包含在表单数据中之前进行编码。表单的时间输入数据条目将始终采用表单 name=hh%3Ammname=hh%3Amm%3Ass(如果包含秒)(请参阅 使用步骤属性)。

¥When a form including a time input is submitted, the value is encoded before being included in the form's data. The form's data entry for a time input will always be in the form name=hh%3Amm, or name=hh%3Amm%3Ass if seconds are included (see Using the step attribute).

附加属性

¥Additional attributes

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

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

注意:与许多数据类型不同,时间值具有周期域,这意味着这些值达到可能的最高值,然后再次回到起点。例如,指定 min14:00max2:00,意味着允许的时间值从下午 2:00 开始,一直持续到午夜到第二天,在凌晨 2:00 结束。请参阅本文的 午夜交叉最小和最大 部分了解更多信息。

¥Note: Unlike many data types, time values have a periodic domain, meaning that the values reach the highest possible value, then wrap back around to the beginning again. For example, specifying a min of 14:00 and a max of 2:00 means that the permitted time values start at 2:00 PM, run through midnight to the next day, ending at 2:00 AM. See more in the making min and max cross midnight section of this article.

list

列表属性的值是位于同一文档中的 <datalist> 元素的 id<datalist> 提供了一个预定义值列表来建议用户进行此输入。列表中与 type 不兼容的任何值都不包含在建议选项中。提供的值是建议,而不是要求:用户可以从此预定义列表中进行选择或提供不同的值。

¥The values of the list attribute is the id of a <datalist> element located in the same document. The <datalist> provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the type are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value.

max

表示最晚接受时间的字符串,在与上述相同的 时间值格式 中指定。如果指定的字符串不是有效时间,则不会设置最大值。

¥A string indicating the latest time to accept, specified in the same time value format as described above. If the specified string isn't a valid time, no maximum value is set.

min

指定最早接受时间的字符串,在前面描述的 时间值格式 中给出。如果指定的值不是有效的时间字符串,则不会设置最小值。

¥A string specifying the earliest time to accept, given in the time value format described previously. If the value specified isn't a valid time string, no minimum value is set.

readonly

布尔属性,如果存在,则意味着用户无法编辑该字段。然而,它的 value 仍然可以通过 JavaScript 代码直接设置 HTMLInputElement value 属性来更改。

¥A Boolean attribute which, if present, means this field cannot be edited by the user. Its value can, however, still be changed by JavaScript code directly setting the HTMLInputElement value property.

注意:由于只读字段不能有值,因此 required 对同时指定了 readonly 属性的输入没有任何影响。

¥Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified.

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.

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

¥For time 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).

any 设置为 step 的值时,使用默认的 60 秒,并且秒值不会显示在 UI 中。

¥When any is set as the value for step, the default 60 seconds is used, and the seconds value is not displayed in the UI.

使用时间输入

¥Using time inputs

时间的基本用途

¥Basic uses of time

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

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

html
<form>
  <label for="appt-time">Choose an appointment time: </label>
  <input id="appt-time" type="time" name="appt-time" />
</form>

控制输入大小

¥Controlling input size

<input type="time"> 不支持诸如 size 之类的表单大小调整属性,因为时间的字符数长度始终大致相同。你必须求助于 CSS 来满足尺码需求。

¥<input type="time"> doesn't support form sizing attributes such as size, since times are always about the same number of characters long. You'll have to resort to CSS for sizing needs.

使用步骤属性

¥Using the step attribute

你可以使用 step 属性来改变每当时间增加或减少时跳跃的时间量(例如,单击小箭头小部件时时间一次移动 10 分钟)。

¥You can use the step attribute to vary the amount of time jumped whenever the time is incremented or decremented (for example, so the time moves by 10 minutes at a time when clicking the little arrow widgets).

它需要一个整数值来定义要增加的秒数;默认值为 60 秒。以此为默认值,大多数用户代理时间 UI 都会显示小时和分钟,但不显示秒。如果 minmax 值尚未导致秒数可见,则将 step 属性包含除 60 整除值以外的任何数值都会将秒数添加到 UI。

¥It takes an integer value defining the number of seconds you want to increment by; the default value is 60 seconds. With this as the default, most user agent time UIs display hours and minutes but not seconds. Including the step attribute with any numeric value other than a value divisible by 60 adds seconds to the UI, if the min or max value has not already caused the seconds to be visible.

html
<form>
  <label for="appt-time">Choose an appointment time: </label>
  <input id="appt-time" type="time" name="appt-time" step="2" />
</form>

要将分钟或小时指定为步骤,请以秒为单位指定分钟或小时数,例如 120 表示 2 分钟,或 7200 表示 2 小时。

¥To specify minutes or hours as a step, specify the number of minutes or hours in seconds, such as 120 for 2 minutes, or 7200 for 2 hours.

验证

¥Validation

默认情况下,<input type="time"> 不对输入的值应用任何验证,除了用户代理界面通常不允许你输入时间值以外的任何内容。这很有用,但你不能完全依赖该值作为正确的时间字符串,因为它可能是一个空字符串 (""),这是允许的。

¥By default, <input type="time"> does not apply any validation to entered values, other than the user agent's interface generally not allowing you to enter anything other than a time value. This is helpful, but you can't entirely rely on the value to be a proper time string, since it might be an empty string (""), which is allowed.

设置最大和最小时间

¥Setting maximum and minimum times

你可以使用 minmax 属性来限制用户可以选择的有效时间。在以下示例中,我们设置最小时间为 12:00,最大时间为 18:00

¥You can use the min and max attributes to restrict the valid times that can be chosen by the user. In the following example we are setting a minimum time of 12:00 and a maximum time of 18:00:

html
<form>
  <label for="appt-time">
    Choose an appointment time (opening hours 12:00 to 18:00):
  </label>
  <input id="appt-time" type="time" name="appt-time" min="12:00" max="18:00" />
  <span class="validity"></span>
</form>

这是上面示例中使用的 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 add an icon as generated content icon on a <span> next to the input.

css
div {
  margin-bottom: 10px;
  position: relative;
}

input[type="number"] {
  width: 100px;
}

input + span {
  padding-right: 30px;
}

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

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

这里的结果是:

¥The result here is that:

  • 仅 12:00 至 18:00 之间的时间被视为有效;超出该范围的时间将被视为无效。

午夜交叉最小和最大

¥Making min and max cross midnight

通过将 min 属性设置为大于 max 属性,有效时间范围将围绕午夜产生有效时间范围。任何其他输入类型均不支持此功能。

¥By setting a min attribute greater than the max attribute, the valid time range will wrap around midnight to produce a valid time range. This functionality is not supported by any other input types.

js
const input = document.createElement("input");
input.type = "time";
input.min = "23:00";
input.max = "01:00";
input.value = "23:59";

if (input.validity.valid && input.type === "time") {
  // <input type=time> reversed range supported
} else {
  // <input type=time> reversed range unsupported
}

所需时间

¥Making times required

此外,你可以使用 required 属性强制填写时间。如果你尝试提交超出设置范围的时间或空的时间字段,浏览器将显示错误。

¥In addition, you can use the required attribute to make filling in the time mandatory. Browsers will display an error if you try to submit a time that is outside the set bounds, or an empty time field.

让我们看一个例子;在这里,我们设置了最小和最大时间,并且还设置了必填字段:

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

html
<form>
  <div>
    <label for="appt-time">
      Choose an appointment time (opening hours 12:00 to 18:00):
    </label>
    <input
      id="appt-time"
      type="time"
      name="appt-time"
      min="12:00"
      max="18:00"
      required />
    <span class="validity"></span>
  </div>
  <div>
    <input type="submit" value="Submit form" />
  </div>
</form>

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

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

警告: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, disaster could strike when improperly-formatted data is submitted (or data which is too large, of the wrong type, and so forth).

示例

¥Examples

在此示例中,我们使用用 <input type="time"> 创建的原生选择器创建了一个用于选择时间的界面元素:

¥In this example, we create an interface element for choosing time using the native picker created with <input type="time">:

HTML

html
<form>
  <label for="appt-time">
    Choose an appointment time (opening hours 12:00 to 18:00):
  </label>
  <input
    id="appt-time"
    type="time"
    name="appt-time"
    min="12:00"
    max="18:00"
    required />
  <span class="validity"></span

CSS

css
input[type="number"] {
  width: 100px;
}

input + span {
  padding-right: 30px;
}

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

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

结果

¥Result

技术摘要

¥Technical Summary

代表时间的字符串或空。
活动 changeinput
支持的通用属性 autocomplete, list, readonly, step
IDL 属性 list, value, valueAsDate, valueAsNumber
DOM 接口

HTMLInputElement

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

规范

Specification
HTML Standard
# time-state-(type=time)

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看