用Javascript将军事时间替换为正常时间 [英] Replace military time to normal time with Javascript

查看:217
本文介绍了用Javascript将军事时间替换为正常时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此脚本

getFormattedTime = function (fourDigitTime){
var hours24 = parseInt(fourDigitTime.substring(0,2));
var hours = ((hours24 + 11) % 12) + 1;
var amPm = hours24 > 11 ? 'pm' : 'am';
var minutes = fourDigitTime.substring(2);

return hours + ':' + minutes + amPm;
};

我可以将4位时间更改为正常时钟时间(尽管有0930的问题..)

I can change 4 digit time to normal clock time (there is a problem with 0930 though..)

这个

$("body").html($("body").html().replace(/1135/g,'11:35am'));

在我的页面中替换1135的任何事件。

To replace any occurange of 1135 in my page.

但是,在我的页面中,我有一个表格中的时间列表。我需要转换它们,例如

However, in my page, I have a list of time in tables. I need to convert them e.g.

Class starts at 1700, please be there by 1630 and sign in by 1645.

它应转换为

Class starts at 05:00pm, please be there by 04:30pm and sign in by 04:45pm.


推荐答案

假设文本中显示的唯一数字是时间您可以使用:

Assuming the only digits displayed in the text are the times you can use:

var txt = 'Class starts at 0845, please be there by 1630 and sign in by 1645.'

getFormattedTime = function (fourDigitTime) {
    var hours24 = parseInt(fourDigitTime.substring(0, 2),10);
    var hours = ((hours24 + 11) % 12) + 1;
    var amPm = hours24 > 11 ? 'pm' : 'am';
    var minutes = fourDigitTime.substring(2);

    return hours + ':' + minutes + amPm;
};
/* replace numeric entities*/
var newTxt = txt.replace(/(\d+)/g, function (match) {
    return getFormattedTime(match)
})
$('body').html(newTxt);

DEMO: http://jsfiddle.net/q6HC9/1

编辑:标记中的包装时间将大大简化情况。用普通类包裹所有军事时间,然后使用 html()方法

Wrapping times in a tag would greatly simplify situation. Wrap all military times in a span with a common class and then use the html() method

<span class="mil_time">0845</span>



getFormattedTime = function (fourDigitTime) {
    /* make sure add radix*/
    var hours24 = parseInt(fourDigitTime.substring(0, 2),10);
    var hours = ((hours24 + 11) % 12) + 1;
    var amPm = hours24 > 11 ? 'pm' : 'am';
    var minutes = fourDigitTime.substring(2);

    return hours + ':' + minutes + amPm;
};
/* find all spans and replace their content*/
$('span.mil_time').html(function( i, oldHtml){
   return getFormattedTime(oldHtml);
})

这篇关于用Javascript将军事时间替换为正常时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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