Javascript: Showing bedtimes in Chart.js

👍:0

When you convert your integer representation of time to “minutes since midnight”, then 2230 lies right in the middle of 2200 and 2300.

var getMinutesSinceMidnight = function(time){
    var hours = Math.floor(time/100);
    var minutes = time%100;    
    return hours*60 + minutes;
}

getMinutesSinceMidnight(2200) //returns 1320 
getMinutesSinceMidnight(2230) //returns 1350 
getMinutesSinceMidnight(2300) //returns 1380

You can use these values for plotting and the original integer times for labeling of the graph.

👍:0

For the hour, divide by 100:

var time = 2330;
var hour = Math.floor(time / 100);

Now subtract the result from the original time and multiply it by the proper fraction (100/60)

time -= (hour * 100)
var minute = (time * 100) / 60

jsfiddle:

window.getTime = function() {
  var time = document.getElementById('time').value;
  var hour = Math.floor(time / 100);
  time -= (hour * 100);
  var minute = (time * 100) / 60;
  alert("Hour: " + hour + ", Minute: " + minute);
}
<input type="number" id="time">
<button type="button" onclick="getTime()">Get Time</button>

This will turn 2330 into 2350, that way the dot appears half-way as expected.

Leave a comment