0

I have string value in this format.

9:00 am

i want it to be like this.

9:00 am - 10:00 am

second hour must be 1 greater then first one. for example if time is

7:00 am then it should be 7:00 am - 8:00 am

how can i do that using jquery? i tried this but its not working as it works now.

var time= "9:00 am"
var nexttime=time.setHours(time.getHours()+1)
 alert(nexttime);

getting error of

time.getHours is not a function
2
  • 5
    And why is this question tagged with PHP? No relation to it. Commented Jan 5, 2017 at 8:06
  • because after adding one hour in it i want to match it with same string in php. Commented Jan 5, 2017 at 8:10

3 Answers 3

2

You can try this :

function increaseTimeByOne(timeStr) {
    var splitedTimeStr = timeStr.split(':');
    var hours = parseInt(splitedTimeStr[0]);
    var meridiem = splitedTimeStr[1].split(" ")[1];
    var minutes = splitedTimeStr[1].split(" ")[0];
    var nextHours = (hours + 1);
    var nextMeridiem;
    if (hours >= 11) {
        if (meridiem.toLowerCase() == "am") {
            nextMeridiem = "pm";
        } else if (meridiem.toLowerCase() == "pm") {
            nextMeridiem = "am";
        }
        if (nextHours > 12) {
            nextHours = nextHours - 12;
        }

    } else {
        nextMeridiem = meridiem;
    }
    return nextHours + ":" + minutes + " " + nextMeridiem;
}

and using above function as

var timestr="9:00 am";
var next_hour = increaseTimeByOne(timeStr);
alert(next_hour);
Sign up to request clarification or add additional context in comments.

9 Comments

your answer seems to be good but i am getting only 10 in alert. i want "10:00 am"
@shahidhamdam can you pls check it now and update the status
sir the answer you have given is working great for am times. but if i select 1:00 pm it shows me 1:00 pm - 2:00 am. can you suggest something?
@shahidhamdam can you pls check it now
if i select 5:00 pm it show me 6:00 am. i need it to show me 6:00 pm.
|
1

refer this

var time=new Date();        
time.setHours(9, 00, 00);
var nexttime=(time.getHours()+1);
alert(nexttime);

// to get hrs mins and seconds

var nexttime=(time.getHours()+1) +":"+time.getMinutes()+":"+time.getSeconds();

Comments

1

YOu can make your time string like:

function increaseTimeByOne(t) {
  var s  = t.split(':');
  var n  = parseInt(s[0], 10);
  var nt = (n + 1) + ":00 ";   
  var ampm = n >= 11 ? "pm" : "am";

  return t + " - " + nt + ampm;
}

console.log(increaseTimeByOne('9:00 am'));
console.log(increaseTimeByOne('11:00 am'));
console.log(increaseTimeByOne('12:00 pm'));

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.