javascript下ie7,ie8的Date Bug的解决 .

本文介绍了一个在IE7及IE8浏览器中解析ISO 8601格式日期字符串为JavaScript Date对象的方法。该方法适用于YYYY-MM-DD格式的日期,并确保了即使在不支持此格式的旧版IE浏览器中也能正确转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


转自:http://blog.youkuaiyun.com/fjh658/article/details/8524530


ie9+, chrome firefox opera下 string到Date 使用   Date("2013-01-01"); 都是ok的。

但在ie7, ie8下 返回NaN


国外有人写了这样一个解决办法

[javascript] view plaincopyprint?
  1. /**Parses string formatted as YYYY-MM-DD to a Date object. 
  2.   * If the supplied string does not match the format, an 
  3.   * invalid Date (value NaN) is returned. 
  4.   * @param {string} dateStringInRange format YYYY-MM-DD, with year in 
  5.   * range of 0000-9999, inclusive. 
  6.   * @return {Date} Date object representing the string. 
  7.   */  
  8.  function parseISO8601(dateStringInRange) {  
  9.    var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,  
  10.        date = new Date(NaN), month,  
  11.        parts = isoExp.exec(dateStringInRange);  
  12.   
  13.    if(parts) {  
  14.      month = +parts[2];  
  15.      date.setFullYear(parts[1], month - 1, parts[3]);  
  16.      if(month != date.getMonth() + 1) {  
  17.        date.setTime(NaN);  
  18.      }  
  19.    }  
  20.    return date;  
  21.  }  
/**Parses string formatted as YYYY-MM-DD to a Date object.
  * If the supplied string does not match the format, an
  * invalid Date (value NaN) is returned.
  * @param {string} dateStringInRange format YYYY-MM-DD, with year in
  * range of 0000-9999, inclusive.
  * @return {Date} Date object representing the string.
  */
 function parseISO8601(dateStringInRange) {
   var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
       date = new Date(NaN), month,
       parts = isoExp.exec(dateStringInRange);

   if(parts) {
     month = +parts[2];
     date.setFullYear(parts[1], month - 1, parts[3]);
     if(month != date.getMonth() + 1) {
       date.setTime(NaN);
     }
   }
   return date;
 }

使用如下:

parseISO8601("2013-01-01");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值