繁体   English   中英

在jQuery和Internet Explorer中将字符串转换为日期?

[英]Convert string to date in jQuery and Internet Explorer?

我想在jQuery中将日期字符串转换为日期对象,下面的代码适用于Chrome和Firefox,但不适用于Internet Explorer:

<script type="text/javascript" charset="utf-8">
//Validate if the followup date is now or passed:
    jQuery.noConflict();
    var now = new Date();
    jQuery(".FollowUpDate").each(function () {
        if (jQuery(this).text().trim() != "") {
            var followupDate = new Date(jQuery(this).text().trim()); //Here's the problem
            alert(followupDate);
            if (followupDate <= now) {
                jQuery(this).removeClass('current');
                jQuery(this).addClass('late');
            }
            else {
                jQuery(this).removeClass('late');
                jQuery(this).addClass('current');
            }
        }
    });
</script>

警报仅用于测试,在Chrome和Firefox中它返回一个日期对象,但在IE中我得到NaN。

有什么问题,我怎样才能进行这种转换,以便在IE中运行?

这个问题帮助我找到了解决我转换日期的问题的方法。 我找到了一种转换日期的方法,无需使用单独的脚本或测试浏览器类型。

以下代码接受格式为2011-01-01(年,月,日)的日期。

function convertDate(stringdate)
{
    // Internet Explorer does not like dashes in dates when converting, 
    // so lets use a regular expression to get the year, month, and day 
    var DateRegex = /([^-]*)-([^-]*)-([^-]*)/;
    var DateRegexResult = stringdate.match(DateRegex);
    var DateResult;
    var StringDateResult = "";

    // try creating a new date in a format that both Firefox and Internet Explorer understand
    try
    {
        DateResult = new Date(DateRegexResult[2]+"/"+DateRegexResult[3]+"/"+DateRegexResult[1]);
    } 
    // if there is an error, catch it and try to set the date result using a simple conversion
    catch(err) 
    { 
        DateResult = new Date(stringdate); 
    }

    // format the date properly for viewing
    StringDateResult = (DateResult.getMonth()+1)+"/"+(DateResult.getDate()+1)+"/"+(DateResult.getFullYear());

    return StringDateResult;
}

希望有所帮助!

如果它是一个看起来像日期的字符串,请使用它。

var followupDate = new Date(Date.Parse(jQuery(this).text().trim()));

我想我应该问的一个问题是,输出是什么

jQuery(this).text().trim()

我想通了:IE显然不接受瑞典日期格式,所以我做了一个字符串替换它接受的格式:

var followupDate = new Date(datestring.replace(' - ','/'));

不幸的是,这种格式不被Firefox接受,因此我必须保留Chrome和Firefox的原始代码,然后使用单独的IE脚本和条件注释。

我没有测试过这个,但是怎么样:

var followupdate = new Date(jQuery(this).text().trim().toString());

toString() ”应该强制它被解释为一个字符串; Date对象应该接受该字符串作为有效输入,它可能会阻止IE引发它。

我用这样的时刻:

new Date(moment(item.ToDate));

与瑞典日期一起使用'2013-01-05':

new Date(moment('2013-01-05'));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM