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

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

 //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'); } } });  

警报仅用于测试,在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'));