使用 javascript 添加 AM/PM
Adding AM/PM using javascript
我有 12 小时格式化时间的简单代码
// This function gets the current time and injects it into the DOM
function updateClock() {
// Gets the current time
var now = new Date();
// Get the hours, minutes and seconds from the current time
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
// Format hours, minutes and seconds
if (hours > 12) {
hours = hours - 12;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
// Gets the element we want to inject the clock into
var elem = document.getElementById('clock');
// Sets the elements inner HTML value to our clock data
elem.innerHTML = hours + ':' + minutes + ':' + seconds ;
}
我想添加上午/下午请提前帮助我谢谢我只是JavaScript的初学者
编辑自己的代码后:
// Get the hours, minutes and seconds from the current time
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var amOrPm = 'AM';
// Format hours, minutes and seconds
if (hours > 12) {
amOrPm = 'PM';
hours = hours - 12;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
// Gets the element we want to inject the clock into
var elem = document.getElementById('clock');
// Sets the elements inner HTML value to our clock data
elem.innerHTML = hours + ':' + minutes + ':' + seconds + ' ' + amOrPm;
试试这个...
var ampm = hours >= 12 ? 'pm' : 'am';
然后
elem.innerHTML = hours + ':' + minutes + ':' + seconds + ' ' + ampm;
我不知道
你是否想自己编码,但有一个非常棒的库,它可以处理你能想象到的日期内容的所有内容。
只需结帐时刻。这是一个简单的 AF 库来转换日期(也在下午/上午)。
如果您有任何问题:)只是评论...
相关文章:
- 用JavaScript将ISO时间转换为H:MM am|pm
- 将带有 AM/PM 的日期字符串转换为 javascript 日期对象
- 如何在JAVASCRIPT中使用格式HH:MM AM/PM将字符串转换为时间
- Javascript格式时间军用am pm从字符串
- Javascript if/else工作不正常[Time Formatting AM/PM]
- 我需要验证时间 AM|PM 的格式
- 如何在时间和子午线(AM?PM)在时钟选择器中
- 在javascript中以“hh:mm:ss am/pm”的格式验证时间
- 在 JavaScript 中以 AM/PM 格式的两个时间之间的差异
- 如何将用户限制为仅输入 12 小时的时间,包括 AM 和 PM
- 如何在 JavaScript 中将时间与 AM PM 进行比较
- jQuery格式化时间以删除秒并添加AM或PM
- 使用moment js将12小时(AM/PM)字符串转换为24日期对象
- Django在表单时间输入中截断am/pm
- 如何在Javascript中使用AM/PM创建时间正则表达式
- 军用和AM/PM onclick之间的Javascript更改时间
- 需要12小时格式而不显示AM/PM时间选择器
- 显示AM/PM的JavaScript打印时间
- 如何使用angular获得AM/PM的12小时格式
- 使用PHP中的java脚本与AM/PM进行12小时的验证