2010-06-18 48 views
0

有兩個字符串(開始和結束時間),形式爲「16:30」,「02:13」我想比較它們並檢查間隔是否大於5分鐘。Javascript,Hour Comparisson

如何以簡單的方式在Javascript中實現?

回答

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

您是否需要在午夜時間換行?那麼這更困難。例如,23:5900:01將產生23小時58分鐘而不是2分鐘的差異。

如果是這種情況,您需要更密切地定義您的案例。

1

你可以做如下:

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

'Date.parse'對於它的輸入並不是很聰明,只接受一些預定義的格式。所以試圖解析純時間組件可能會失敗,你應該提供一個日期上下文Date.parse(「01/01/2010」+「16:30」)' – Andris 2010-06-18 09:30:09

1
// 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); 
} 

減去次迫使對象通過調用valueOf方法返回以毫秒爲單位給定的時間來評估它的價值。 minutes方法是將給定分鐘數轉換爲毫秒的另一種便利方法,因此我們可以將其用作比較基準。

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

這包括檢查午夜是否在兩次之間(按照您的示例)。

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."); 
} 
相關問題