开发者

Javascript, Hour comparisson

开发者 https://www.devze.com 2023-01-04 10:01 出处:网络
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.

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?


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.


You can do as following:

if (((Date.parse("16:30") - Date.parse("02:13")) / 1000 / 60) > 5)
{
}


// 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


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.");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消