user3199857 user3199857 - 2 months ago 7
Javascript Question

quarter hour wont be accurate

Why wont quarterHours show me 1,2,3,4? or all of the numbers?
im trying to get each 15 minutes.

is the nextlaunch not calculating the next 15 minute right?

why, wont it calculate the next 15 minutes correctly ?

Im expecting it quarterHours to output all the 15 minutes.

X:15 = 1
X:30 = 2
X:45 = 3
X:00 = 4 or 0


current outcome:

4/9/2016 @ 18:30:0
fiddle.jshell.net/:60 2
fiddle.jshell.net/:59 4/9/2016 @ 18:30:0
fiddle.jshell.net/:60 2
fiddle.jshell.net/:59 4/9/2016 @ 18:30:0
fiddle.jshell.net/:60 2
fiddle.jshell.net/:59 4/9/2016 @ 19:0:0
fiddle.jshell.net/:60 0


fiddle: https://jsfiddle.net/g2x1jmzb/

code:

var y = 1;

while(y <= 4) {
var interval = (900000 * y);
var nextlaunch = new Date(Math.ceil(new Date().getTime()/interval)*interval);
var datetime = "" + nextlaunch.getDate() + "/"
+ (nextlaunch.getMonth()+1) + "/"
+ nextlaunch.getFullYear() + " @ "
+ nextlaunch.getHours() + ":"
+ nextlaunch.getMinutes() + ":"
+ nextlaunch.getSeconds();

quarterHours = Math.round(nextlaunch.getMinutes()/15);
console.log(datetime);
console.log(quarterHours);
y++;
}

Answer

You could use this code:

function pad(n) {
    return ('0'+n).substr(-2);
}
   
var interval = 15 * 60 * 1000; // = # miliseconds in 15 minutes
var nextlaunch = new Date(Math.ceil(new Date().getTime()/interval)*interval);
for (var y = 1; y <= 4; y++) {
    var datetime = pad(nextlaunch.getDate()) + "/"
                + pad((nextlaunch.getMonth()+1))  + "/" 
                + nextlaunch.getFullYear() + " @ "  
                + pad(nextlaunch.getHours()) + ":"  
                + pad(nextlaunch.getMinutes()) + ":" 
                + pad(nextlaunch.getSeconds());
    quarterHours = Math.round(nextlaunch.getMinutes()/15);
    console.log(datetime);
    nextlaunch.setMinutes(nextlaunch.getMinutes()+15);
}

The idea is that you increase the nextlaunch variable in the loop by adding 15 minutes to it. Its initial value can be set outside of the loop, with the use of the appropriate interval.

I added a function to do proper padding with zeroes in the date format. You might consider using a library to work with dates, like moment.js.

Comments