views:

47

answers:

4

Having two strings (start and end time) in such form "16:30", "02:13" I want to compare them and check if the gap is greater than 5 mins.

How can this be achieved in Javascript in an easy way?

+2  A: 
function parseTime(time) {
  var timeArray = time.split(/:/);
  // Using Jan 1st, 2010 as a "base date". Any other date should work.
  return new Date(2010, 0, 1, +timeArray[0], +timeArray[1], 0);
}

var diff = Math.abs(parseTime("16:30").getTime() - parseTime("02:13").getTime());
if (diff > 5 * 60 * 1000) { // Difference is in milliseconds
  alert("More that 5 mins.");
}

Do you need to wrap over midnight? Then this is more difficult. For example, 23:59 and 00:01 will produce a difference of 23 hours 58 minutes and not 2 minutes.

If that's the case you need to define your case more closely.

RoToRa
+1  A: 

You can do as following:

if (((Date.parse("16:30") - Date.parse("02:13")) / 1000 / 60) > 5)
{
}
Cliffwolf
`Date.parse` is not very smart about the input it gets and accepts only some predefined formats. So trying to parse plain time component probably fails and you should provide a date context too `Date.parse("01/01/2010 "+"16:30")`
Andris
+1  A: 
// time is a string having format "hh:mm"
function Time(time) {
    var args = time.split(":");
    var hours = args[0], minutes = args[1];

    this.milliseconds = ((hours * 3600) + (minutes * 60)) * 1000;
}

Time.prototype.valueOf = function() {
    return this.milliseconds;
}

// converts the given minutes to milliseconds 
Number.prototype.minutes = function() {
    return this * (1000 * 60);
}

Subtracting the times forces the object to evaluate it's value by calling the valueOf method that returns the given time in milliseconds. The minutes method is another convenience method to convert the given number of minutes to milliseconds, so we can use that as a base for comparison throughout.

new Time('16:30') - new Time('16:24') > (5).minutes() // true
Anurag
+1  A: 

This includes checking whether midnight is between the two times (as per your example).

var startTime = "16:30", endTime = "02:13";

var parsedStartTime = Date.parse("2010/1/1 " + startTime),
    parsedEndTime = Date.parse("2010/1/1 " + endTime);

// if end date is parsed as smaller than start date, parse as the next day,
// to pick up on running over midnight
if ( parsedEndTime < parsedStartTime ) ed = Date.parse("2010/1/2 " + endTime);

var differenceInMinutes = ((parsedEndTime - parsedStartTime) / 60 / 1000);
if ( differenceInMinutes > 5 ) {
   alert("More than 5 mins.");
}
Mario Menger