【发布时间】:2015-11-15 02:08:00
【问题描述】:
此函数将时间转换为 12 小时格式,感谢 Stack Overflow 上此函数的贡献者:
JS
function ampm(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // 0 should be 12
minutes = minutes < 10 ? '0'+minutes : minutes; // if minutes less than 10, add a 0 in front of it ie: 6:6 -> 6:06
var strTime = hours + ':' + minutes + ' ' + ampm;
document.getElementById('time').value = strTime;
return strTime;
}
////This is how the value of the time input is supposed to be displayed in 12 hr format
_("display_time").innerHTML = ampm(new Date());
HTML
<!--This is the input field where a user selects a time-->
<input id="time" placeholder="Time" type="time" name="time" />
<!--This is where the value of the time input is supposed to be displayed in 12 hr format-->>
<span id="display_time"></span>
我的问题是如何让时间输入字段的值以 12 小时格式显示在跨度标签上。这段代码是半工作的。
它以 12 小时格式显示时间,但仅显示当前时间。流程图类似于,用户选择时间输入 -> 一些 JS 转换为 12hr 格式 -> 在 span 标签中显示为 12hr 格式。有什么意见或建议吗?
【问题讨论】:
-
老实说,这似乎让你的生活变得复杂。有很多关于时间和日期对象的 stackoverflow 问题提出了更简单的解决方案。你只需要搜索一下。
-
你打算如何让用户“选择时间输入”?那个时间是什么格式(字符串?时间?时间戳?)
标签: javascript html time