Javascript Date(dateString)返回特定服务器和浏览器上的NaN [英] Javascript Date(dateString) returns NaN on specific server and browser

查看:104
本文介绍了Javascript Date(dateString)返回特定服务器和浏览器上的NaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用日期格式为yyyy-mm-dd的Javascript Date(string)构造函数。构造函数在IE 9和Firefox中工作正常,除非应用程序在运行IIS的测试VM上运行。如果它在虚拟机上,则在IE 9中返回NaN,但仍可在Firefox中正常工作。

I'm using the Javascript Date(string) constructor with a date format of "yyyy-mm-dd". The constructor works just fine in IE 9 and Firefox unless the app is running on our testing VM which is running IIS. If it's on the VM, in IE 9 it returns 'NaN', but still works normally in Firefox.

    var dateAsString = "2011-11-09";
    var dateCreated = new Date(dateAsString);

我假设服务器与客户端Javascript无关。任何建议?

I was under the assumption that the server had nothing to do with client-side Javascript. Any suggestions?

推荐答案

我建议尝试更可靠的日期解析形式。以下示例使用 setFullYear()。 IE是否产生与以下代码不同的结果?

I suggest attempting a more reliable form of date parsing. The example below uses setFullYear(). Does IE produce a different result with the code below?

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

资料来源: http://jibbering.com/faq/#parseDate

这篇关于Javascript Date(dateString)返回特定服务器和浏览器上的NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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