BenNov
BenNov

Reputation: 1111

JavaScript Calculate time difference in known intervals

I'm Struggling with calculation of date time objects :(

We're getting three inputs from the user:

1. Start time of day
2. End time of day
3. Intervals between events (in minutes)

My target goal is to calculate how many events I have every day from start time to end time by the selected interval, and creating an array with the exact times of these events.

So far I'm getting the data in this way:

StartTime is a Datetime object. EndTime is a Datetime object.

//Get start time    
var HourOfStart = StartTime.getHours();
var MinuteOfStart = StartTime.getMinutes();

//Get end time    
var HourOfEnd = EndTime.getHours();
var MinuteOfEnd = EndTime.getMinutes();

After calculating the differences of how many events in an hour and trying to cap the first and last events, I realised I must be doing something wrong (math is not my strong suit). Also converting to a unix timestamp got me baffled, because the events aren't starting at a round hour.

So in a nutshell, if the user enters:

Start time: 10:15
End time: 12:30
Interval: 15 minutes

I need to get the following array of event times: 10:30,10:45,11:00,11:15,11:30,11:45,12:00,12:15

Thanks!!

Upvotes: 0

Views: 2343

Answers (1)

Dave
Dave

Reputation: 10924

Here's a function that should do what you want. As suggested in the comments, just calculate the time in milliseconds and increment until you reach your stop time.

function calculate() {
  var a = [];
  var startValue = document.getElementById("startTime").value;
  var endValue = document.getElementById("endTime").value;
  var intervalValue = document.getElementById("interval").value;
  var startDate = new Date("1/1/2015 " + startValue);
  var endDate = new Date("1/1/2015 " + endValue);
  var offset = intervalValue * 1000 * 60;
  do {
    startDate = new Date(startDate.getTime() + offset);
    if (startDate < endDate)
      a.push(startDate);
  } while(startDate < endDate);
  console.log(a);
}
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<label for="startTime">Start Time</label>
<input id="startTime" value="10:15" />
<br/>
<label for="endTime">End Time</label>
<input id="endTime" value="12:30" />
<br/>
<label for="interval">Interval</label>
<input id="interval" value="15" />
<br/>
<input type="button" onclick="calculate()" value="Calculate" />

Upvotes: 1

Related Questions