How to add 30 minutes to a specified time (min & max time) in javascript.For example: I have start time as 03:00 AM and end time as 05:00 PM and I need to add 30minutes from start time to end time.
Asked
Active
Viewed 111 times
-5
-
What have you tried? We expect people to at least make an effort and post what they done so far. Also, a Google search of your title will help you no end, but funnily enough, that was a no effort question too, but got over 600 up-votes... – Ken Y-N Nov 29 '18 at 06:08
-
This seems like a really simple math problem.... What *exactly* are you having trouble figuring out? – Claies Nov 29 '18 at 06:09
-
2Possible duplicate of [How to add 30 minutes to a JavaScript Date object?](https://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object) – Ken Y-N Nov 29 '18 at 06:10
1 Answers
0
You can achieve this by spliting the Time
this is how it can be done
var startTime = '03:00 AM';
var newStartTime = startTime;
var endTime = '05:00 AM';
var minutes=0;
var hours=0;
var timeArray=[];
var ampm='';
var executing=true;
while(executing) {
timeArray.push(newStartTime);
minutes = Number(minutes) + 30;
hours = newStartTime.split(' ')[0].split(':')[0]
ampm= newStartTime.split(' ')[1];
if(minutes > 59) {
if(Number(hours) > 12) {
ampm = newStartTime.split(' ')[1] == 'AM'?'PM':'AM';
hours = '01';
}
else {
hours = Number(hours) + 1;
if(hours.toString().length ==1) {
hours = '0' + hours;
}
}
minutes = minutes - 60;
}
if(minutes.toString().length ==1) {
minutes = '0' + minutes;
}
newStartTime = hours + ':' + minutes+' ' +ampm;
if(Number(newStartTime.split(' ')[0].split(':')[0]) > Number(endTime.split(' ')[0].split(':')[0])){
if(newStartTime.split(' ')[1] == endTime.split(' ')[1])
executing = false;
}
else if(Number(newStartTime.split(' ')[0].split(':')[0]) == Number(endTime.split(' ')[0].split(':')[0])) {
if(Number(newStartTime.split(' ')[0].split(':')[1]) >= Number(endTime.split(' ')[0].split(':')[1])) {
if(newStartTime.split(' ')[1] == endTime.split(' ')[1])
executing = false;
}
}
}
timeArray.push(endTime);
here is a small JsFiddle for you
you can do the same with endTime,
there are many other ways to do this and this is one of those,
hope this solve your problem,
-
This works for adding 30 minutes to the time we are giving. But I am expecting like, if start time is 03:00AM and end time is 05:00PM, i need to get as 03:00AM, 03:30AM, 04:00AM, 04:30AM..........05:00PM. – Nandha Nov 29 '18 at 06:38
-
-
Sure. I have two time (start & end). I need to add 30 minutes each from start time till it reaches the end time. For example start time is 3:00Am and end time is 5:00PM. So I need an output as 3:00AM, 3:30AM, 4;00AM and till reaches 5:00PM. Hope you get it? – Nandha Nov 29 '18 at 06:48