2013-09-25 71 views
6

我有兩個時間,格式爲「HH:MM」我想對它們進行比較,我有下面的代碼來獲得現在的時間在我的格式:如何在JavaScript中比較時間?

current_time = new Date(); 
hour = current_time.getHours(); 
minute = current_time.getMinutes(); 
if(hour<10){hour='0'+hour} if(minute<10){minute='0'+minute} 
my_time = hour+':'+minute; 

而且這個代碼後獲取時間減去GMT差異:

d = new Date() 
var n = d.getTimezoneOffset(); 
var n1 = Math.abs(n); 
var difference = (n1/60); 
my_time = my_time - (0+difference); 

現在my_time的值應該與match_time的值進行比較:

match_time = 10:00;//for example 
if(my_time > match_time) 
{ 
    alert('yes'); 
} 
else 
{ 
    alert('No'); 
} 

我怎麼能比較這些值作爲TI我當他們是一個字符串?

回答

4
Date.parse('25/09/2013 13:31') > Date.parse('25/09/2013 9:15') 

編輯:

注意你解析你是不感興趣的任意日期,它只需要在兩側是相同的。

+0

Date.parse是依賴於實現,在這種情況下,會在某些瀏覽器(如Safari瀏覽器)都將返回NaN。 OP可以直接將字符串作爲字符串進行比較。 – RobG

1
if(Date.parse('01/01/2011 10:20:45') == Date.parse('01/01/2011 5:10:10')) { 
    alert('same'); 
    }else{ 

    alert('different'); 

    } 

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

使用日期對象。 Date.setHours()允許你如果我有足夠的代表把票投給@Gabo Esquivel的解決方案指定小時,分鐘,秒

var currentD = new Date(); 
var startHappyHourD = new Date(); 
startHappyHourD.setHours(17,30,0); // 5.30 pm 
var endHappyHourD = new Date(); 
endHappyHourD.setHours(18,30,0); // 6.30 pm 

console.log("happy hour?") 
if(currentD >= startHappyHourD && currentD < endHappyHourD){ 
    console.log("yes!"); 
}else{ 
    console.log("no, sorry! between 5.30pm and 6.30pm"); 
} 
+0

我知道這個問題問如何比較字符串,但我認爲這是一個更好的解決方案的整體問題。 –

0

。幾天來我一直在尋找和測試解決方案,這是唯一一個適合我的解決方案。

我需要一個條件語句來測試當前時間是否爲0830,如果是,請執行一些操作。我的if語句不起作用,所以我需要其他例子來處理。

//Business Hours: Saturday 8:30am-12pm; highlight Saturday table row. 
function showSaturdayHours() { 
    var today = new Date(); 
    var weekday = today.getDay(); 
    var saturdayOpen = new Date(); 
    saturdayOpen.setHours(8, 30, 0); 
    var saturdayClose = new Date(); 
    saturdayClose.setHours(12, 0, 0); 

if (weekday == 6) { 
    $('#saturday-row').addClass('row-blue'); //highlight table row if current day is Saturday. 
    if (today >= saturdayOpen && today < saturdayClose) { 
     document.getElementById('saturday-open').innerHTML = 'Open'; 
    } else { 
     document.getElementById('saturday-open').innerHTML = 'Closed'; 
    } 
    } 
} 

營業時間表:JSFiddle