2012-09-23 49 views
0

目前,我有以下腳本:的Javascript時間比較

<script> 
if(new Date().getHours() > 17 || (new Date().getHours() == 17 &&  
new Date().getMinutes()== 0 && new Date().getSeconds() == 0) && 
(new Date().getHours() < 21 && new Date().getMinutes() < 30 
&& new Date().getSeconds() == 0)){ 
     //do nothing. 
    } else { 
    $(document).ready(function() { 
     $(".inline").colorbox({inline:true, open:true, width:"50%"}); 
     }); 
    } 

所以basicly什麼立場的,如果: 如果時間爲17:00至21:30,什麼也不做,要不然顯示框。但是發生什麼事情是,盒子在18:00左右停止工作,並再次在午夜工作..有人看到這裏有什麼錯誤?

回答

0
var d = new Date(); 

if (d.getHours() < 17 || 
    d.getHours() > 21 || 
    (d.getHours() == 21 && d.getMinutes() >= 30)) { 

     $(document).ready(function() { 
      $(".inline").colorbox({inline:true, open:true, width:"50%"}); 
     }); 
} 
+0

比我的更優雅的17和21小時你的標誌是不是逆轉? –

+1

@Likwid_T:不,我爲了擺脫空的'if'條件結果'//不做任何事'而反轉了邏輯。行爲應該在17:00之前和21:30之後或之後發生。 –

+0

你說得對,我的壞 –

1
$(document).ready(function() 
{ 
    var now = new Date(), 
     block = $('div'); 

    if(now.getHours() >= 17 && (now.getHours() < 21 || (now.getHours() == 21 && now.getMinutes() <= 30))) 
    { 
     block.text('17:00 - 21:30'); 
     //do nothing.  
    } 
    else 
    { 
     block.text('not 17:00 - 21:30'); 
     //$(".inline").colorbox({inline:true, open:true, width:"50%"}); 
    } 
}); 

演示:http://jsfiddle.net/FwtRb/10/

+1

對不起,但這是不正確的。它將在每個小時的後半部分而不是僅在21小時內失效。 –

+0

@ user1689607謝謝,我解決了它。 – webdeveloper

1

注意,在日期(包括小時)許多領域是0索引。這就是爲什麼你觀察這個停止在18:00左右工作。

我建議使用變量來使條件更簡單的理由。嘗試這樣的事情。如果您擔心命名空間污染,請在其周圍封閉。

var now = new Date(); 
var startQuietPeriod = new Date(); 
startQuietPeriod.setHours(16); startQuietPeriod.setMinutes(0); startQuietPeriod.setSeconds(0); startQuietPeriod.setMilliseconds(0); // Today at 17:00 
var endQuietPeriod = new Date(); 
endQuietPeriod.setHours(20); endQuietPeriod.setMinutes(30); endQuietPeriod.setSeconds(0); endQuietPeriod.setMilliseconds(0); // Today at 21:30 
if (startQuietPeriod < now && now < endQuietPeriod) { 
    // don't show prompt 
} else { 
    // show prompt 
} 
1

這是我怎麼會這樣寫:

var now = new Date(); 

if (now.getHours() >= 17 && now.getHours() <= 21) { 
    if (now.getHours() == 21 && now.getMinutes() > 30) { 
     return; 
    } 
} 

// Do your document.ready stuff here 

首先,我做了當前時間保存到一個變量,它使我少打字(記住:是一個懶惰的打字員)。此外,這也會清理你的狀況,所以更容易發現任何邏輯錯誤。

其次,我將你的條件(17:00和21:30之間無所作爲)分成2個獨立的條件。就我個人而言,我更喜歡這種方式,因爲即使您在2年後回到代碼中,它也毫無意義。
您的代碼只能讀取。永遠記住這一點。如果條件複雜,即使評論得很好,也會在未來讓你和其他人感到困難。忽略那些給你打電話的人。

另外我發現它更易於使用return,如果條件匹配,它會簡單地中止當前函數/ <script>。這樣可以節省1個縮進級別:-)

更新:你也應該閱讀peakxu's answer(因此MDN page for Date)。請注意,正如peakxu所說,所有這些都是0索引。