2010-10-29 75 views
3

我想一个日期字符串转换为jQuery的日期对象,下面的代码工作正常,Chrome和Firefox,但不是在Internet Explorer中:在jQuery和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中工作?

回答

6

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

下面的代码接受格式为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; 
} 

希望有所帮助!

+0

这是一种到现在为止,我已经开始了:-)但无论如何,我会在某个时候尝试一下! – Anders 2011-02-16 07:20:46

+0

这基本上工作。现在让我们说,我有两个增值税从这个返回的值....可以从彼此扣除? – WilfredMifsud 2012-01-25 14:20:54

+0

如果它们由此函数返回,则它们可能无法相互扣除,因为该函数返回一个字符串。我建议在调用这个函数前在日期做任何数学运算。 – 2012-01-25 14:26:16

1

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

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

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

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

输出?

+0

不幸的是,这给了我完全相同的结果(NAN)。 jQuery(this).text()。trim()的输出是表格单元格的内容,它是瑞典日期格式(“2010-10-30”)中的日期字符串。火狐和铬没有问题,并立即把它变成一个日期对象,但IE似乎并没有认出它或什么... – Anders 2010-10-30 09:56:54

1

我想通了:IE浏览器显然没有接受瑞典的日期格式,所以我做了一个字符串替换为一种格式它确实接受:

VAR followupDate =新的日期(datestring.replace(“ - ”, '/'));

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

+0

或使用isNan(日期)条件分开ie /其他浏览器 – 2011-04-18 07:23:12

1

我没有测试过这一点,但如何:

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

的“toString()”应该强迫它被解释为一个字符串; Date对象应该接受这个字符串作为有效的输入,并且可能会阻止IE向上抛出。

0

我用像这样的时刻:

new Date(moment(item.ToDate)); 

厂与瑞典的日期,以及 '2013年1月5日':

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