JavaScript new Date() Returning NaN in IE or Invalid Date in Safari

在JS中,如果使用new Date()时传入字符串参数,如:

<pre name="code" class="javascript">var date = new Date("2015-04-08");
 

在chrome、Firefox下会返回对应的日期,但是在IE8及以下,会返回NaN;在Safari下会返回Invalid Date。

此时需要对参数进行转换,网上对此转换的方法如下:

/**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;
  }
使用时,把日期字符串作为参数传给该方法即可。

var date = parseISO8601("2015-01-02");
这样就能得到想要的结果了。




参考链接:http://stackoverflow.com/questions/2182246/javascript-dates-in-ie-nan-firefox-chrome-ok

                      http://jibbering.com/faq/#parseDate



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值