2011-07-09 78 views

回答

11

DEMO HERE

我喜歡有日期的對象,但在其他地方所指出的,你可以轉換到秒,如果你想要做簡單的比較

function dateCompare(time1,time2) { 
    var t1 = new Date(); 
    var parts = time1.split(":"); 
    t1.setHours(parts[0],parts[1],parts[2],0); 
    var t2 = new Date(); 
    parts = time2.split(":"); 
    t2.setHours(parts[0],parts[1],parts[2],0); 

    // returns 1 if greater, -1 if less and 0 if the same 
    if (t1.getTime()>t2.getTime()) return 1; 
    if (t1.getTime()<t2.getTime()) return -1; 
    return 0; 
} 

alert(dateCompare("12:40:13","20:01:01")); 

爲秒:

function dateDiff(time1,time2) { 
    var t1 = new Date(); 
    var parts = time1.split(":"); 
    t1.setHours(parts[0],parts[1],parts[2],0); 
    var t2 = new Date(); 
    parts = time2.split(":"); 
    t2.setHours(parts[0],parts[1],parts[2],0); 

    return parseInt(Math.abs(t1.getTime()-t2.getTime())/1000); 
} 

假設你有24小時的時間和相同的填充,你可以做簡單的字符串比較

var t1 = "12:40:13", t2= "20:01:01"; 
if (t1<t2) { 
    console.log(t1," is < ", t2); 
} 
1

這裏有一個建議,我從this website here的解決方案中修改,希望它有幫助。

function compareTime(time_1, time_2) { 
    var s1 = 
     time1.split(":")[0] * 3600 + time1.split(":")[1] * 60 + time1.split(":")[2]; 
    var s2 = 
     time2.split(":")[0] * 3600 + time2.split(":")[1] * 60 + time1.split(":")[2]; 
    return Math.abs(s1 - s2); // Gets difference in seconds 
} 

var time_1 = "12:40:13", time_2 = "20:01:01"; 
document.write(compareTime(time_1, time_2)); 
6

如果「比較」的意思是「看看他們是平等的」,兩個具有相同的格式,爲什麼不乾脆:

var time1 = "12:40:13"; 
var time2 = "20:01:01"; 

if (time1 == time2) { 
    // do stuff 
} 

如果你需要得到時間的不同,轉換到一個日期對象是單向的(見mplungjan的答案),或者你可以將它們轉換爲公共單位(比如秒)和減:

function toSeconds(t) { 
    var bits = t.split(':'); 
    return bits[0]*3600 + bits[1]*60 + bits[2]*1; 
} 

var secs1 = toSeconds(time1); 
var secs2 = toSeconds(time2); 

// do stuff - compare, subtract, less than, greater than, whatever 
+0

是啊,我總是讓約會對象 - 但顯然它並不總是必要的 – mplungjan

+0

這很好,我只是想提供一個非日期的選擇。 – RobG

+0

這比製作日期對象要快多少? – Whitecat

1

這裏的另一種看法:

function compareTimes(timeOne, timeTwo) {   
    if(daterize(timeOne) > daterize(timeTwo)) return 1; 
    if(daterize(timeOne) < daterize(timeTwo)) return -1; 
    return 0; 
} 

function daterize(time) { 
    return Date.parse("Thu, 01 Jan 1970 " + time + " GMT"); 
} 

您可能還想看看MDN Javascript docs for Dates。 JavaScript帶有很多陷阱,比如Date.month會從0到11。

1
Date.parse('01/01/2011 10:20:45') > Date.parse('01/01/2011 5:10:10') 

The 1st January is an arbitrary date, doesn't mean anything.