Skip to content

time 时间输入

<input type="time"> 是 HTML5 引入的时间选择控件,允许用户通过浏览器内置的时间选择器选择一个具体的时间(时:分)。该控件自动处理时间格式,支持 12 小时制和 24 小时制显示,提交流程中统一为 HH:MMHH:MM:SS 格式。

前置知识

阅读本节前,建议先了解:date 日期输入

基础概念

什么是 time 输入

type="time" 输入框提供了一个专门用于选择时间的界面。与使用文本框手动输入时间相比,time 输入具有以下优势:

  • 内置时间控件:点击输入框弹出时间选择器,方便选择
  • 格式统一:提交值始终为 HH:MMHH:MM:SS 格式
  • 自动验证:无法选择不存在的时间(如 25:00)
  • 步进精度:可通过 step 属性控制分钟或秒的精度
  • 移动端优化:在移动设备上显示原生时间滚轮选择器

浏览器支持

浏览器支持情况控件外观
Chrome✅ 完整支持时间滚动控件
Firefox✅ 完整支持时间输入框
Safari✅ 支持(14.1+)时间滚轮
Edge✅ 完整支持时间滚动控件
Opera✅ 完整支持时间滚动控件

提交值格式

time 输入提交的值遵循 24 小时制格式:

HH:MM       —— 仅小时和分钟(默认)
HH:MM:SS    —— 包含秒(step 设置为秒级时)

例如:09:30 表示上午 9 点 30 分,14:00 表示下午 2 点整。

语法

基本用法

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>time 时间输入示例</title>
</head>
<body>
    <h2>选择时间</h2>
    <form>
        <label for="alarm">闹钟时间:</label>
        <input type="time" id="alarm" name="alarm">
        <button type="submit">设置闹钟</button>
    </form>
</body>
</html>

设置默认值

通过 value 属性设置默认时间:

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>time 默认值示例</title>
</head>
<body>
    <h2>默认工作时间</h2>
    <form>
        <label for="work-start">上班时间:</label>
        <!-- 默认值设置为 09:00 -->
        <input type="time" id="work-start" name="work_start" value="09:00">

        <label for="work-end">下班时间:</label>
        <!-- 默认值设置为 18:00 -->
        <input type="time" id="work-end" name="work_end" value="18:00">
        <button type="submit">保存</button>
    </form>
</body>
</html>

min 和 max 属性

限制可选时间范围:

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>time 范围限制</title>
</head>
<body>
    <h2>预约时间段</h2>
    <form>
        <p>预约时间为 09:00 至 18:00:</p>
        <label for="appointment">预约时间:</label>
        <input
            type="time"
            id="appointment"
            name="appointment"
            min="09:00"
            max="18:00"
            required
        >
        <button type="submit">预约</button>
    </form>
</body>
</html>
属性说明格式
min最小可选时间HH:MMHH:MM:SS
max最大可选时间HH:MMHH:MM:SS

详细说明

step 步进控制

step 属性控制时间选择的精度(单位为秒):

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>time step 示例</title>
</head>
<body>
    <h2>不同精度的 时间选择</h2>
    <form>
        <div>
            <label for="time-minute">分钟精度(默认 step=60):</label>
            <!-- step=60 表示每分钟可选,用户选择小时和分钟 -->
            <input type="time" id="time-minute" name="time_minute" step="60">
        </div>

        <div>
            <label for="time-quarter">15 分钟间隔(step=900):</label>
            <!-- 15 分钟 = 900 秒,选择器只显示 00, 15, 30, 45 分 -->
            <input type="time" id="time-quarter" name="time_quarter" step="900">
        </div>

        <div>
            <label for="time-second">秒级精度(step=1):</label>
            <!-- step=1 允许选择秒数 -->
            <input type="time" id="time-second" name="time_second" step="1">
        </div>

        <div>
            <label for="time-any">任意精度(step=any):</label>
            <!-- step=any 不限制精度 -->
            <input type="time" id="time-any" name="time_any" step="any">
        </div>
    </form>
</body>
</html>

常用 step 值对照表

step 值(秒)含义选择器显示
11 秒时:分:秒
60(默认)1 分钟时:分
3005 分钟每 5 分钟一档
90015 分钟00, 15, 30, 45
180030 分钟00, 30
36001 小时只选整点
any不限完全自由输入

12 小时制与 24 小时制

浏览器根据用户操作系统的语言和地区设置来决定时间选择器的显示格式:

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>12/24 小时制</title>
</head>
<body>
    <h2>时间显示格式</h2>
    <form>
        <p>以下输入框根据您的系统设置显示:</p>

        <label for="time-input">选择时间:</label>
        <input type="time" id="time-input" name="time">

        <p id="format-info"></p>
    </form>

    <script>
        const timeInput = document.getElementById('time-input');
        const formatInfo = document.getElementById('format-info');

        timeInput.addEventListener('change', function () {
            // 无论显示为 12 还是 24 小时制,value 始终是 24 小时制
            formatInfo.textContent = `提交值(24小时制):${this.value}`;
        });
    </script>
</body>
</html>

注意:无论用户界面显示为 12 小时制(AM/PM)还是 24 小时制,value 属性返回的始终是 24 小时制格式。例如,用户选择"下午 2:30",value"14:30"

valueAsDate 与 valueAsNumber

<input type="time"> 提供了两个特殊属性来读取时间值:

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>time 值属性示例</title>
</head>
<body>
    <h2>获取时间值的不同方式</h2>

    <label for="my-time">选择时间:</label>
    <input type="time" id="my-time" name="my_time" value="14:30">

    <div id="output"></div>

    <script>
        const timeInput = document.getElementById('my-time');
        const output = document.getElementById('output');

        timeInput.addEventListener('input', function () {
            // 方式一:value 字符串
            const timeStr = this.value; // "14:30"

            // 方式二:valueAsDate — 返回一个 Date 对象(日期部分为 1970-01-01)
            const timeDate = this.valueAsDate;

            // 方式三:valueAsNumber — 返回自午夜以来的毫秒数
            const timeNum = this.valueAsNumber; // 52200000 (14.5 * 3600 * 1000)

            // 从 Date 对象提取时和分
            const hours = timeDate ? timeDate.getHours() : 0;
            const minutes = timeDate ? timeDate.getMinutes() : 0;

            output.innerHTML = `
                <p>value 字符串:${timeStr}</p>
                <p>小时:${hours},分钟:${minutes}</p>
                <p>距离午夜的毫秒数:${timeNum}</p>
                <p>距离午夜的小时数:${(timeNum / 3600000).toFixed(2)}</p>
            `;
        });
    </script>
</body>
</html>

JavaScript 操作时间

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>JavaScript 操作时间</title>
</head>
<body>
    <h2>时间操作工具</h2>
    <form>
        <div>
            <label for="start-time">开始时间:</label>
            <input type="time" id="start-time" name="start_time" value="09:00">
        </div>
        <div>
            <label for="duration">时长(小时):</label>
            <input type="number" id="duration" name="duration" value="8" min="0.5" max="24" step="0.5">
        </div>
        <button type="button" id="calc-btn">计算结束时间</button>
        <div>
            <label for="end-time">结束时间:</label>
            <input type="time" id="end-time" name="end_time" readonly>
        </div>
    </form>

    <script>
        document.getElementById('calc-btn').addEventListener('click', function () {
            const startTime = document.getElementById('start-time');
            const duration = document.getElementById('duration');
            const endTime = document.getElementById('end-time');

            if (startTime.value && duration.value) {
                // 获取开始时间的毫秒数
                const startMs = startTime.valueAsNumber || 0;

                // 计算结束时间的毫秒数
                const durationMs = parseFloat(duration.value) * 3600000;
                const endMs = startMs + durationMs;

                // 处理跨天情况
                const totalMinutesInDay = 86400000;
                const adjustedMs = endMs % totalMinutesInDay;

                // 创建临时 Date 对象来格式化
                const tempDate = new Date(adjustedMs + new Date().getTimezoneOffset() * 60000);
                const endHour = tempDate.getHours().toString().padStart(2, '0');
                const endMinute = tempDate.getMinutes().toString().padStart(2, '0');

                endTime.value = `${endHour}:${endMinute}`;
            }
        });
    </script>
</body>
</html>

实战示例

会议预约系统

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>会议预约</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
            max-width: 700px;
            margin: 40px auto;
            padding: 0 20px;
        }
        .form-group { margin-bottom: 16px; }
        label { display: block; margin-bottom: 6px; font-weight: 600; }
        input, select {
            padding: 8px 12px;
            border: 2px solid #ddd;
            border-radius: 6px;
            font-size: 16px;
        }
        input:focus, select:focus {
            border-color: #6f42c1;
            outline: none;
        }
        .time-slots {
            margin-top: 16px;
            padding: 16px;
            background: #f3f0ff;
            border-radius: 8px;
        }
        .slot {
            display: inline-block;
            margin: 4px;
            padding: 6px 14px;
            background: #fff;
            border: 2px solid #6f42c1;
            border-radius: 20px;
            cursor: pointer;
            font-size: 14px;
        }
        .slot:hover { background: #6f42c1; color: #fff; }
        .slot.selected { background: #6f42c1; color: #fff; }
    </style>
</head>
<body>
    <h2>会议预约</h2>
    <form id="meeting-form">
        <div class="form-group">
            <label for="meeting-date">会议日期:</label>
            <input type="date" id="meeting-date" name="meeting_date" required>
        </div>
        <div class="form-group">
            <label for="meeting-start">开始时间:</label>
            <input
                type="time"
                id="meeting-start"
                name="meeting_start"
                min="09:00"
                max="18:00"
                step="1800"
                required
            >
        </div>
        <div class="form-group">
            <label for="meeting-duration">会议时长:</label>
            <select id="meeting-duration" name="duration">
                <option value="30">30 分钟</option>
                <option value="60" selected>1 小时</option>
                <option value="90">1.5 小时</option>
                <option value="120">2 小时</option>
            </select>
        </div>
        <button type="submit">预约会议</button>
    </form>

    <div class="time-slots" id="time-slots">
        <h3>快速选择时间段</h3>
        <div id="slots-container"></div>
    </div>

    <script>
        const startInput = document.getElementById('meeting-start');
        const durationSelect = document.getElementById('meeting-duration');
        const slotsContainer = document.getElementById('slots-container');

        // 生成可用时间段(每 30 分钟一个)
        function generateTimeSlots() {
            const slots = [];
            for (let hour = 9; hour <= 18; hour++) {
                for (let minute = 0; minute < 60; minute += 30) {
                    if (hour === 18 && minute > 0) break;
                    const h = hour.toString().padStart(2, '0');
                    const m = minute.toString().padStart(2, '0');
                    slots.push(`${h}:${m}`);
                }
            }
            return slots;
        }

        // 渲染时间段
        const slots = generateTimeSlots();
        slots.forEach(slot => {
            const span = document.createElement('span');
            span.className = 'slot';
            span.textContent = slot;
            span.addEventListener('click', function () {
                startInput.value = slot;
                // 更新选中状态
                document.querySelectorAll('.slot').forEach(s => s.classList.remove('selected'));
                this.classList.add('selected');
            });
            slotsContainer.appendChild(span);
        });

        // 设置日期最小值为今天
        const today = new Date().toISOString().split('T')[0];
        document.getElementById('meeting-date').min = today;

        // 表单提交
        document.getElementById('meeting-form').addEventListener('submit', function (e) {
            e.preventDefault();
            const date = document.getElementById('meeting-date').value;
            const time = startInput.value;
            const duration = durationSelect.value;
            alert(`会议预约成功!\n日期:${date}\n时间:${time}\n时长:${duration} 分钟`);
        });
    </script>
</body>
</html>

注意事项

step 值为 1 时的秒级输入

step="1" 时,时间选择器会显示秒数输入。提交值格式变为 HH:MM:SS

html
<!-- 包含秒的时间选择 -->
<input type="time" name="timer" step="1" value="00:05:30">
<!-- 提交值:00:05:30 -->

valueAsNumber 的特殊行为

valueAsNumber 返回的是从午夜(00:00:00)到所选择时间的毫秒数。当输入为空时,返回 NaN

javascript
const timeInput = document.getElementById('my-time');

// 14:30 的毫秒数
// 14 * 3600 * 1000 + 30 * 60 * 1000 = 52200000
console.log(timeInput.valueAsNumber); // 52200000

// 空值
timeInput.value = '';
console.log(timeInput.valueAsNumber); // NaN

不能选择跨天时间

type="time" 只表示一天内的时间点,不表示持续时间。如果需要表示持续多天的时间,应使用其他方式(如单独的天数字段加时间字段)。

列表属性 list

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>time 列表建议</title>
</head>
<body>
    <h2>常用时间快速选择</h2>
    <form>
        <label for="work-time">工作时间:</label>
        <input type="time" id="work-time" name="work_time" list="time-suggestions">
        <datalist id="time-suggestions">
            <option value="08:00">
            <option value="08:30">
            <option value="09:00">
            <option value="09:30">
            <option value="10:00">
            <option value="17:00">
            <option value="17:30">
            <option value="18:00">
            <option value="18:30">
        </datalist>
    </form>
</body>
</html>

最佳实践

  1. 合理设置 step:根据业务场景选择合适的时间精度,预约类场景用 30 分钟步进,计费类用分钟级
  2. 配合 min/max 使用:对于有营业时间等限制的场景,设置时间范围约束
  3. 快速选择功能:使用 datalist 提供常用时间快速选择,提升用户体验
  4. 显示格式考虑:虽然提交值统一为 24 小时制,但应考虑面向用户展示时的可读性
  5. 跨时区场景:如果应用涉及多时区,需要在服务端处理时区转换,time 输入不包含时区信息
  6. 与 date 配合:当需要完整日期时间时,使用 datetime 分别选择,或使用 datetime-local

下一节

继续学习:datetime-local 日期时间输入

参考链接