2014-12-04 63 views
2

我有這個代碼,我只想出現在某個日期。哪些代碼在Firefox,Chrome甚至是Safari瀏覽器中都能正常工作。但是代碼不適用於IE。我不知道爲什麼。IE沒有正確比較日期字符串

我發現IE中的.toLocaleString()用空格而不是逗號分隔它們。

function givingTuesdayCode(){ 
    var isIE = /*@[email protected]*/false || !!document.documentMode; 
    var now = calcTime(-6); 
    var splitnow = ""; 
    if (isIE){ splitnow = now.split(" "); } 
    else{ splitnow = now.split(","); } 

    if (splitnow[0] == "12/2/2014"){ 

     $('.introrotation').html("<img style='width:100%; height:auto' class='givingTuesday' src='/graphics/PoliticGov_620x265.jpg' alt='Give to us'/> <a href='http://IllinoisState.edu/GivingTuesday' class='GiveButtonLink'>Giving Tuesday: Join us!</a> <p style='color:black; position:relative; top:-85px; margin:10px'>Black Friday and Cyber Monday have come and gone. Today, join your fellow Redbirds and make a gift that matters. Give today at <a href='http://IllinoisState.edu/GivingTuesday' class='GiveLink'>IllinoisState.edu/GivingTuesday</a></p>"); 
      $('.introrotation').css({'height': '265px' 
       }); 
      $('.toggleButton').css({'display': 'none' 
       }); 
    } 

    function calcTime(offset){ 
    var date = new Date(); 
    var utc = date.getTime()+(360*60000); 
    var nd = new Date(utc+(3600000*offset)); 
    return nd.toLocaleString(); 
    } 
+1

您獲得的價值和預期的價值是什麼? – ArinCool 2014-12-04 17:58:12

+0

爲什麼不直接使用'.toLocaleDateString'方法呢?另外,如果您打算使用* locale字符串*,您應該提及您想使用的語言環境。 「2014年12月2日」是你用'en-US'得到的,但'en-GB'將返回「02/12/2014」。避免將日期作爲字符串進行比較可能更爲明智。 – Sampson 2014-12-04 19:20:29

回答

2

,而不是試圖日期匹配到一個特定的字符串(可能在其他語言環境破),只需直接比較的具體日期:

// Reset the hours, minutes, etc. so that comparison works 
var today = (new Date()).setHours(0, 0, 0, 0); 

// Month is zero-indexed (i.e. 0 = Jan, 11 = Dec) 
var specificDate = (new Date(2014, 11, 2)).getTime(); 

if (today === specificDate) { 
    $('.introrotation').html("<img style='width:100%; height:auto' class='givingTuesday' src='/graphics/PoliticGov_620x265.jpg' alt='Give to us'/> <a href='http://IllinoisState.edu/GivingTuesday' class='GiveButtonLink'>Giving Tuesday: Join us!</a> <p style='color:black; position:relative; top:-85px; margin:10px'>Black Friday and Cyber Monday have come and gone. Today, join your fellow Redbirds and make a gift that matters. Give today at <a href='http://IllinoisState.edu/GivingTuesday' class='GiveLink'>IllinoisState.edu/GivingTuesday</a></p>"); 
    $('.introrotation').css({'height': '265px'}); 
    $('.toggleButton').css({'display': 'none'}); 
} 

關於比較日期的詳細信息,請參閱Compare two dates with JavaScript

理想情況下,您應該在服務器端而不是客戶端執行此操作,以便您的消息仍顯示禁用JavaScript的瀏覽器。