With this script
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;
};
I can change 4 digit time to normal clock time (there is a problem with 0930 though..)
And with this
$("body").html($("body").html().replace(/1135/g,'11:35am'));
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.
It should translate into
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
EDIT: 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);
})
Use this:
var 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;
};
s = "Class starts at 1700, please be there by 1630 and sign in by 1645.";
c = s.replace(/([^\d]*)([0-9]{4})([^\d]*)/g, function(match, p1, p2, p3) {
return p1 + getFormattedTime(p2) + p3
});
console.log(c);
Output:
Class starts at 5:00pm, please be there by 4:30pm and sign in by 4:45pm.
Update
In your case:
s = $("body").html();
c = s.replace(/([^\d]*)([0-9]{4})([^\d]*)/g, function(match, p1, p2, p3) {
return p1 + getFormattedTime(p2) + p3
});
$("body").html(c);
Update 2
If you have the time inside <td class="fourDigitTime">1500</td>
, then use this:
$(".fourDigitTime").each(function() {
$(this).text(getFormattedTime($(this).text());
});
Live Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With