如何使用jQuery为datetime-local输入框的时间增加2小时?
实现datetime-local输入框自动追加2小时功能
我有两个datetime-local类型的输入框:
- id为
DeliveryTime的输入框支持用户修改 - id为
DeliveryTimeEnd的输入框为只读状态
需求是:当DeliveryTime的时间发生变更时,自动将DeliveryTimeEnd的时间设置为前者的时间加2小时。
原尝试代码
HTML结构
<input class="form-control" type="datetime-local" name="deliveryTime" id="DeliveryTime" required> <input class="form-control" type="datetime-local" name="deliveryTimeEnd" id="DeliveryTimeEnd" readonly>
jQuery代码
$("#DeliveryTime").on("change", function() { var startTime = $("#DeliveryTime").val(); startTime.setHours(startTime.getHours()+2); alert(startTime); $("#DeliveryTimeEnd").val(startTime); });
问题分析
原代码的核心问题是:$("#DeliveryTime").val()返回的是字符串格式的时间值(例如"2024-05-20T14:30"),并非Date对象,因此直接调用setHours()方法会触发错误——字符串没有该方法。
修正后的代码
$("#DeliveryTime").on("change", function() { // 获取当前输入的时间字符串 const startTimeStr = $(this).val(); // 若输入为空,直接返回避免报错 if (!startTimeStr) return; // 将字符串转为Date对象 const startTime = new Date(startTimeStr); // 给时间增加2小时 startTime.setHours(startTime.getHours() + 2); // 把Date对象转为datetime-local要求的格式(YYYY-MM-DDTHH:mm) const endTimeStr = startTime.toISOString().slice(0, 16); // 设置到只读输入框中 $("#DeliveryTimeEnd").val(endTimeStr); });
关键说明
- 必须将输入的时间字符串转为
Date对象,才能进行时间增减操作 datetime-local输入框要求的格式是YYYY-MM-DDTHH:mm,因此需要用toISOString()生成标准格式后,截取前16位字符- 增加空值判断,防止用户清空输入时出现异常
内容的提问来源于stack exchange,提问作者sameera kularathna
相关产品推荐
相关产品推荐

