【问题标题】:IE not comparing date strings correctlyIE 没有正确比较日期字符串
【发布时间】:2014-12-04 17:55:35
【问题描述】:

我有这个代码,我只想在某个日期出现。这段代码在 Firefox、Chrome 甚至 safari 中运行良好。但是,该代码不适用于 IE。我也不知道为什么。

我发现 IE 中的 .toLocaleString() 用空格而不是逗号分隔它们。

  function givingTuesdayCode(){
     var isIE = /*@cc_on!@*/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();
  }

【问题讨论】:

  • 你得到的价值是什么,期望是什么?
  • 为什么不直接使用.toLocaleDateString 方法呢?此外,如果您要使用 locale 字符串,您应该提及您想使用的语言环境。使用en-US 会得到“12/2/2014”,但类似en-GB 的内容将返回“02/12/2014”。避免将日期作为字符串进行比较可能更明智。

标签: javascript string internet-explorer date


【解决方案1】:

不要尝试将日期与特定字符串匹配(这可能会在其他语言环境中中断),而是直接比较特定日期:

// 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 的浏览器中显示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 2014-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多