2

Im trying to store values in an Array using a loop in JavaScript. It only works partially for me.

I want to store time in an Array

There will be startTime, endTime and an interval

For example: If want to get the time from 9:00 to 10:00 with an interval of 15 minutes, it should print

09:00,09:15,09:30,09:45,10:00

but it's printing

09:00,09:15,09:30,09:45,10:00,10:15,10:30,10:45

Second what should I do if I want to get the time difference between 9:30 and 10:30? or 9:45 and 10:45?

Here is my Code:

HTML

<div id="time"></div>

JavaScript

var array = new Array();
var timeDiff = 15;
var FirstTime = 9;
var endTime = 10;
for (var xh = FirstTime; xh <= endTime; xh++) {
    for (var xm = 0; xm < 60; xm += timeDiff) {
        array.push(("0" + xh).slice(-2) + ':' + ("0" + xm).slice(-2));
    }
};
$('#time').text(array)

JsFiddle

5 Answers 5

2

Hi i have created a jsfiddle example:-

var setIntervals = function (start, end, inc) {
    start = start.toString().split(':');
    end = end.toString().split(':');
    inc = parseInt(inc, 10);

    var pad = function (n) { return (n < 10) ? '0' + n.toString() : n; },
        startHr = parseInt(start[0], 10),
        startMin = parseInt(start[1], 10),
        endHr = parseInt(end[0], 10),
        endMin = parseInt(end[1], 10),
        currentHr = startHr,
        currentMin = startMin,
        previous = currentHr + ':' + pad(currentMin),
        current = '',
        r = [];

    do {
        currentMin += inc;
        if ((currentMin % 60) === 0 || currentMin > 60) {
            currentMin = (currentMin === 60) ? 0 : currentMin - 60;
            currentHr += 1;
        }
        current = currentHr + ':' + pad(currentMin);
        r.push(previous + ' - ' + current);
        previous = current;
  } while (currentHr !== endHr);

    return r;
};

click here to see example:-http://jsfiddle.net/w6EQ6/3/

or if you don't want to print the range then see the below given link:-

http://jsfiddle.net/w6EQ6/6/

fixed the issue:http://jsfiddle.net/w6EQ6/8/

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

6 Comments

Really nice Work but time is showing in range. Can we show it like,9:15,9:30,9:45,10:00?
i have added new jsfiddle link it will return the desired output please check my answer...
Its not working when u choose time between 9:30 to 10:30
i fixed that..see my answer.
please check compare all the results with console.time.i am using pure calculation so it will be faster then using Date.. First link:-jsfiddle.net/w6EQ6/10/show using calculation second link:-jsfiddle.net/w6EQ6/11/show with date object check both jsfiddles in firefix and see the time in console.and if you want to see the code then remove the show from url.thanks
|
2

Well , if you need you to make your loop stop in 10:00 here is the code

   var array = new Array();
    var timeDiff = 15;
    var end = 10;
    var start = 9;
    for (var xh = start; xh <= end; xh++) {
        for (var xm = 0; xm < 60; xm += timeDiff) {
            array.push(("0" + xh).slice(-2) + ':' + ("0" + xm).slice(-2));
             if(xh==end)
                break;
        }
    };

now if you want to calculate the difference between two dates here is the function

    function difference(date1,date2)
    {
        date1 = new Date(0,0,0,parseInt(date1.split(":")[0]),parseInt(date1.split(":")[1]));
        date2 = new Date(0,0,0,parseInt(date2.split(":")[0]),parseInt(date2.split(":")[1]));
        diff = (((date1>date2)?1:-1)*(date1-date2))/(1000*60*60);
        return diff;
    }

you can use this function like this

var diff = difference(array[0],array[1]); //for example

This function returns the difference in hours if you need in minutes or secondes you have to change the diff variable like this

// in minutes
diff = (((date1>date2)?1:-1)*(date1-date2))/(1000*60);
            return diff;
// in seconds
diff = (((date1>date2)?1:-1)*(date1-date2))/1000;
            return diff;

Here is a jsFiddle

1 Comment

Really nice suggestion brother. But this what i was looking jsfiddle.net/w6EQ6/3
2

Here is an answer that works for 9:30 to 10:30 using one of the answers here:

function padLeft(value, padding) {
    return String(padding + value).slice(-padding.length);
}

function getTimeInterval(start, end, interval) {
    var result = [];

    var date = new Date();
    date.setHours(start.hour);
    date.setMinutes(start.minute);


    while (!(date.getHours() === end.hour && date.getMinutes() === end.minute + interval)) {
        result.push(padLeft(date.getHours(), '00') + ':' + padLeft(date.getMinutes(), '00'));
        date = new Date(date.getTime() + interval * 60 * 1000);
    }
    return result;


}
console.log(getTimeInterval({
    hour: 9,
    minute: 30
}, {
    hour: 10,
    minute: 30
}, 15));

1 Comment

One Work For You! GREAT
1

You are looping one extra, below code will solve your problem

for (var xh = FirstTime; xh < endTime; xh++) {
    for (var xm = 0; xm < 60; xm += timeDiff) {
        array.push(("0" + xh).slice(-2) + ':' + ("0" + xm).slice(-2));
    }
};
array.push(("0" + xh).slice(-2)+':' + ("00").slice(-2));

and updated jsfiddle

1 Comment

Thank you for your help but 10:00 is still missing
0

The problem is with your nesting of for loops. What happens in you code is that the inner loop is executed twice. Once while xh=9 and once when xh=10. This is why you are getting more times than you expect.

One fix would be to change

xh <= endTime

to

xh < endTime

This would result in every time up to endTime being printed. To make it inclusive, I would add another line to add the endTime to the array.

So your final loop might look like

for (var xh = FirstTime; xh < endTime; xh++) {
    for (var xm = 0; xm < 60; xm += timeDiff) {
        array.push(("0" + xh).slice(-2) + ':' + ("0" + xm).slice(-2));
    }
    array.push(("0" + endTime).slice(-2) + ':' + ("00").slice(-2));
};

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.