日期构造函数在 IE 中返回 NaN,但在 Firefox 和 Chrome 中有效 [英] Date constructor returns NaN in IE, but works in Firefox and Chrome

查看:39
本文介绍了日期构造函数在 IE 中返回 NaN,但在 Firefox 和 Chrome 中有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 JavaScript 构建一个小日历.我的日期在 Firefox 和 Chrome 中运行良好,但在 IE 中,日期函数返回 NaN.

I'm trying to build a little calendar in JavaScript. I have my dates working great in Firefox and Chrome, but in IE the date functions are returning NaN.

这是函数:

function buildWeek(dateText){
    var headerDates='';
    var newDate = new Date(dateText);

    for(var d=0;d<7;d++){
        headerDates += '<th>' + newDate + '</th>';
        newDate.setDate(newDate.getDate()+1);
    }                       

    jQuery('div#headerDates').html('<table><tr>'+headerDates+'</tr></table>');
}

dateText 是当前周的星期一,它实际上是在php中以'm, d, Y'的格式设置的,例如02, 01, 2010".

dateText is the Monday of the current week which is actually set in php in the format of 'm, d, Y', e.g. "02, 01, 2010".

推荐答案

Date 构造函数接受任何值.如果参数的原始 [[value]] 是数字,则创建的日期具有该值.如果原始 [[value]] 为 String,则规范仅保证 Date 构造函数和 parse 方法能够解析 Date.prototype.toString 和 Date.prototype.toUTCString() 的结果

The Date constructor accepts any value. If the primitive [[value]] of the argument is number, then the Date that is created has that value. If primitive [[value]] is String, then the specification only guarantees that the Date constructor and the parse method are capable of parsing the result of Date.prototype.toString and Date.prototype.toUTCString()

设置日期的一种可靠方法是构造一个日期并使用 setFullYearsetTime 方法.

A reliable way to set a Date is to construct one and use the setFullYear and setTime methods.

此处显示了一个示例:http://jibbering.com/faq/#parseDate

ECMA-262 r3 没有定义任何日期格式.将字符串值传递给 Date 构造函数或 Date.parse 具有依赖于实现的结果.最好避免.

ECMA-262 r3 does not define any date formats. Passing string values to the Date constructor or Date.parse has implementation-dependent outcome. It is best avoided.


comp.lang.javascript FAQ 中的条目是:扩展的 ISO 8601 本地日期格式 YYYY-MM-DD 可以解析为 Date,如下所示:-


The entry from comp.lang.javascript FAQ is: An Extended ISO 8601 local date format YYYY-MM-DD can be parsed to a Date with the following:-

/**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})-(dd)-(dd)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;
  }

这篇关于日期构造函数在 IE 中返回 NaN,但在 Firefox 和 Chrome 中有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆