How we can add hours into 12hour format time using Javascript/JQuery?
Example:
Add 2 hour in 12:00 AM then result should be 02:00 AM
Add 8 hour in 09:00 PM then result should be 05:00 AM
Advertisement
Answer
The following function takes a string representing a time and an integer denoting the number of hours you want to add to that time. You can optionally pass an integer number of minutes as well. The result is a string formatted as ‘h:mm xm’.
JavaScript
x
40
40
1
function addTimeToString(timeString, addHours, addMinutes) {
2
// The third argument is optional.
3
if (addMinutes === undefined) {
4
addMinutes = 0;
5
}
6
// Parse the time string. Extract hours, minutes, and am/pm.
7
var match = /(d+):(d+)s+(w+)/.exec(timeString),
8
hours = parseInt(match[1], 10) % 12,
9
minutes = parseInt(match[2], 10),
10
modifier = match[3].toLowerCase();
11
// Convert the given time into minutes. Add the desired amount.
12
if (modifier[0] == 'p') {
13
hours += 12;
14
}
15
var newMinutes = (hours + addHours) * 60 + minutes + addMinutes,
16
newHours = Math.floor(newMinutes / 60) % 24;
17
// Now figure out the components of the new date string.
18
newMinutes %= 60;
19
var newModifier = (newHours < 12 ? 'AM' : 'PM'),
20
hours12 = (newHours < 12 ? newHours : newHours % 12);
21
if (hours12 == 0) {
22
hours12 = 12;
23
}
24
// Glue it all together.
25
var minuteString = (newMinutes >= 10 ? '' : '0') + newMinutes;
26
return hours12 + ':' + minuteString + ' ' + newModifier;
27
}
28
29
function test(timeString, addHours, addMinutes) {
30
document.write(timeString + ' + ' + addHours + ' h ' +
31
(addMinutes || 0) + ' m → ' +
32
addTimeToString(timeString, addHours, addMinutes) + '<br>');
33
}
34
35
test('11:30 AM', 1, 45);
36
test('9:00 PM', 4);
37
test('11:55 PM', 0, 5); // In five minutes it will be midnight: 12 am.
38
test('12:00 AM', 0, 5); // Five minutes after midnight: 12:05 am.
39
test('11:55 AM', 0, 5); // In five minutes it will be noon: 12 pm.
40
test('12:00 PM', 0, 5); // Five minutes after noon: 12:05 pm.