Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

Add hours in 12 hour format using javascript / jquery

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'.

function addTimeToString(timeString, addHours, addMinutes) {
  // The third argument is optional.
  if (addMinutes === undefined) {
    addMinutes = 0;
  }
  // Parse the time string. Extract hours, minutes, and am/pm.
  var match = /(d+):(d+)s+(w+)/.exec(timeString),
      hours = parseInt(match[1], 10) % 12,
      minutes = parseInt(match[2], 10),
      modifier = match[3].toLowerCase();
  // Convert the given time into minutes. Add the desired amount.
  if (modifier[0] == 'p') {
    hours += 12;
  }
  var newMinutes = (hours + addHours) * 60 + minutes + addMinutes,
      newHours = Math.floor(newMinutes / 60) % 24;
  // Now figure out the components of the new date string.
  newMinutes %= 60;
  var newModifier = (newHours < 12 ? 'AM' : 'PM'),
      hours12 = (newHours < 12 ? newHours : newHours % 12);
  if (hours12 == 0) {
    hours12 = 12;
  }
  // Glue it all together.
  var minuteString = (newMinutes >= 10 ? '' : '0') + newMinutes;
  return hours12 + ':' + minuteString + ' ' + newModifier;
}

function test(timeString, addHours, addMinutes) {
  document.write(timeString + ' + ' + addHours + ' h ' +
      (addMinutes || 0) + ' m &rarr; ' +
      addTimeToString(timeString, addHours, addMinutes) + '<br>');
}

test('11:30 AM', 1, 45);
test('9:00 PM', 4);
test('11:55 PM', 0, 5);  // In five minutes it will be midnight: 12 am.
test('12:00 AM', 0, 5);  // Five minutes after midnight: 12:05 am.
test('11:55 AM', 0, 5);  // In five minutes it will be noon: 12 pm.
test('12:00 PM', 0, 5);  // Five minutes after noon: 12:05 pm.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...