-2

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

4
  • What you have tried yet ?? Commented Apr 9, 2015 at 4:50
  • You need to write some code to achieve it. It is not right out of the box in JavaScript Commented Apr 9, 2015 at 4:51
  • Added sample code below :) Commented Apr 9, 2015 at 5:06
  • it depends what you want to get when adding 2 hours to 11PM. If you need to have it roll to next date then you have to convert original time to Date object, add 2 hours and then convert back to string. Commented Apr 9, 2015 at 5:12

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You have a slight error there: based on this function, 12:00 AM will get as next hour 1 PM, which is wrong. The hours go from 12:00 AM through 11 AM, then change to 12:00 PM through 11 PM. So your code should change to: if (hours == '12' && modifier[0] == 'a') { hours = 24; } else if (modifier[0] == 'p' && hours < 12) { hours += 12; }
Thanks for pointing out the bug. It can be fixed by taking the number of hours modulo 12: hours = parseInt(match[1], 10) % 12. It is an interesting quirk of traditional time notation that twelve actually means zero.
0

function formatTime(date) {

    var meridiem = 'AM',
        hours;
    
    // Add the hours
    date.setHours(date.getHours() + 2);

    hours = date.getHours();

    if (hours >= 12) {
        meridiem = 'PM';
        hours = hours % 2;
    }
    
    hours = (hours === 0) ? 12 : hours;   
    
    return formatNumber(hours) + ':' + formatNumber(date.getMinutes()) + ' ' + meridiem;

}

function formatNumber(number) {
    return ('0' + number).slice(-2);
}

alert(formatTime(new Date()));

3 Comments

For padding 0 you can also use ('0' + number).slice(-2)
This code depends on current time only, as i mentioned i want it depends on user wanted time and get time according to it.
@phpboy Currently i am passing current time as function parameter. Pass user wanted time as parameter instead
0

I've added a couple of methods to the Date prototype class.

//Complete Solution

Date.createDateFromTime = function(hours, minutes) {
  var date = new Date();
  date.setTime(hours, minutes);

  return date;
}

Date.prototype.setTime = function(hours, minutes) {
  this.setHours(hours);
  this.setMinutes(minutes);

  return this.displayTime();
}

Date.prototype.displayTime = function() {
  function addZero(number) {
    if (number < 10) {
      return "0" + number.toString();
    } else {
      return number.toString();
    }
  }

  var hours = this.getHours();
  var minutes = this.getMinutes();
  var am_pm = "AM";

  if (hours >= 12) {
    am_pm = "PM"
    hours -= 12;
  }

  if (hours == 0) hours = 12;

  hours = addZero(hours);
  minutes = addZero(minutes);

  return hours + ":" + minutes + " " + am_pm;
}

Date.prototype.addHours = function(hours) {
  this.setHours(this.getHours() + hours);

  return this.getHours();
}

//Examples

date = Date.createDateFromTime(19, 20);
console.log(date.displayTime()); // "07:20 PM"
date.addHours(4);
console.log(date.displayTime()); // "11:20 PM"
date.addHours(5);
console.log(date.displayTime()); // "04:20 AM"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.