如何使用javascript将时间从24小时格式转换为12小时格式? [英] How to convert time from 24 hour format to 12 hour format using javascript?

查看:106
本文介绍了如何使用javascript将时间从24小时格式转换为12小时格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该函数以24小时格式返回时间。

The function returns the time in 24 hour format.

function fomartTimeShow(h) {
    return h < 10 ? "0" + h + ":00" : h + ":00";
}

以24小时格式返回时间。我希望时间以12小时格式转换。

Anyhelp将不胜感激。

谢谢。

returns the time in 24 hour format. I want the time to be converted in 12 hour format.
Anyhelp would be greatly appreciated.
Thanks.

推荐答案

只需使用模数12:

function formatTimeShow(h_24) {
    var h = h_24 % 12;
    return (h < 10 ? '0' : '') + h + ':00';
}

模数( )意味着分而为余。例如17/12 = 1,余数为5.因此17%12的结果为5.而小时17是12小时内的小时5。

Modulus (%) means divide and take remainder. For example 17 / 12 = 1 with remainder 5. So the result of 17 % 12 is 5. And hour 17 is hour 5 in 12-hour time.

但请注意此功能未完成,因为它不适用于小时0(或小时12)。要修复它,你必须添加另一个检查:

But note that this function is not complete since it doesn't work for hour 0 (or hour 12). To fix it you have to add in another check for that:

function formatTimeShow(h_24) {
    var h = h_24 % 12;
    if (h === 0) h = 12;
    return (h < 10 ? '0' : '') + h + ':00';
}

另请注意,您可以通过查看小时是否轻松添加子午线小于12(上午)或等于/大于(下午):

Also note that you can add a meridian easily, by seeing whether the hour is less than 12 (am) or equal to/greater (pm):

function formatTimeShow(h_24) {
    var h = h_24 % 12;
    if (h === 0) h = 12;
    return (h < 10 ? '0' : '') + h + ':00' + (h_24 < 12 ? 'am' : 'pm');
}

注意:上述所有内容都假定此函数的参数是0到23之间的整数。

这篇关于如何使用javascript将时间从24小时格式转换为12小时格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆