2010-02-02 34 views
70

我正在嘗試在JavaScript中構建一個小日曆。我的日期在Firefox和Chrome中運行良好,但在IE中日期函數返回NaN。日期構造函數在IE中返回NaN,但在Firefox和Chrome中可用

下面是函數:

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是被在「米,d,Y」的格式在PHP實際設定的當前周的星期一,例如"02, 01, 2010"

+2

您對您的代碼示例一些複製粘貼錯誤,看看for語句:'爲(VAR d = 0; d';',這將提高一個'SyntaxError' ... – CMS 2010-02-02 06:36:59

回答

62

Date構造函數接受任何值。如果參數的原始[[value]]是數字,那麼創建的Date就有該值。如果primitive [[value]]是String,那麼規範只保證Date構造函數和解析方法能夠解析Date.prototype.toString和Date.prototype.toUTCString()的結果。一種可靠的方法設置日期是構建一個並使用setFullYearsetTime方法。

這方面的一個例子出現在這裏: http://jibbering.com/faq/#parseDate

ECMA-262 R3沒有定義任何日期格式。將字符串值傳遞給Date構造函數或Date.parse具有實現相關結果。這是最好的避免。


編輯: 從comp.lang.javascript FAQ的條目是: 一個擴展的ISO 8601的本地日期格式 YYYY-MM-DD可以被解析到一個 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; 
    } 
+0

謝謝Garrett。你在鏈接中提供的這個功能比我能找到的任何其他功能都要簡潔得多,而且它適用於我通過其他99%應用程序使用的日期格式。我正在使用 – pedalpete 2010-02-02 18:32:49

+0

這是唉,不好,因爲許多結構化的格式只是使用W3C日期/時間格式(ISO-8601,全規格左右)。所以雖然時間戳在很多方面都更好(更簡單,更高效,適用於所有瀏覽器),但通常需要標準日期/時間數據是來自javascript的解析器。 我不知道,如果jQuery或這樣會有更好的解析方法。 – StaxMan 2010-05-27 20:05:23

+3

感謝指出,瘋了爲什麼鉻工作正常解析日期,而IE7說NAN,好東西$ jQuery的$ .datepicker.parseDate能夠解析日期 – 2012-10-30 08:37:36

0

JavaScript中的Date構造函數需要一個parse()方法支持的日期格式之一的字符串。

顯然,您指定的格式在IE中不受支持,因此您需要更改PHP代碼或手動解析JavaScript中的字符串。

+4

這一點是很明顯,但是知道支持哪些格式可能是很好的... – StaxMan 2010-05-27 20:06:55

1

在下面的方法中發送您要發送datetext的日期文本和格式。它會解析並返回日期,這與瀏覽器無關。

function cal_parse_internal(val, format) { 
val = val + ""; 
format = format + ""; 
var i_val = 0; 
var i_format = 0; 
var x, y; 
var now = new Date(dbSysCurrentDate); 
var year = now.getYear(); 
var month = now.getMonth() + 1; 
var date = now.getDate(); 

while (i_format < format.length) { 
    // Get next token from format string 
    var c = format.charAt(i_format); 
    var token = ""; 
    while ((format.charAt(i_format) == c) && (i_format < format.length)) { 
     token += format.charAt(i_format++); 
    } 
    // Extract contents of value based on format token 
    if (token == "yyyy" || token == "yy" || token == "y") { 
     if (token == "yyyy") { x = 4; y = 4; } 
     if (token == "yy") { x = 2; y = 2; } 
     if (token == "y") { x = 2; y = 4; } 
     year = _getInt(val, i_val, x, y); 
     if (year == null) { return 0; } 
     i_val += year.length; 
     if (year.length == 2) { 
      if (year > 70) { 
       year = 1900 + (year - 0); 
      } else { 
       year = 2000 + (year - 0); 
      } 
     } 
    } else if (token == "MMMM") { 
     month = 0; 
     for (var i = 0; i < MONTHS_LONG.length; i++) { 
      var month_name = MONTHS_LONG[i]; 
      if (val.substring(i_val, i_val + month_name.length) == month_name) { 
       month = i + 1; 
       i_val += month_name.length; 
       break; 
      } 
     } 
     if (month < 1 || month > 12) { return 0; } 
    } else if (token == "MMM") { 
     month = 0; 
     for (var i = 0; i < MONTHS_SHORT.length; i++) { 
      var month_name = MONTHS_SHORT[i]; 
      if (val.substring(i_val, i_val + month_name.length) == month_name) { 
       month = i + 1; 
       i_val += month_name.length; 
       break; 
      } 
     } 
     if (month < 1 || month > 12) { return 0; } 
    } else if (token == "MM" || token == "M") {  
     month = _getInt(val, i_val, token.length, 2); 
     if (month == null || month < 1 || month > 12) { return 0; } 
     i_val += month.length; 
    } else if (token == "dd" || token == "d") { 
     date = _getInt(val, i_val, token.length, 2); 
     if (date == null || date < 1 || date > 31) { return 0; } 
     i_val += date.length; 
    } else { 
     if (val.substring(i_val, i_val+token.length) != token) {return 0;} 
     else {i_val += token.length;} 
    } 
} 

// If there are any trailing characters left in the value, it doesn't match 
if (i_val != val.length) { return 0; } 

// Is date valid for month? 
if (month == 2) { 
    // Check for leap year 
    if ((year%4 == 0 && year%100 != 0) || (year%400 == 0)) { // leap year 
     if (date > 29) { return false; } 
    } else { 
     if (date > 28) { return false; } 
    } 
} 
if (month == 4 || month == 6 || month == 9 || month == 11) { 
    if (date > 30) { return false; } 
} 
return new Date(year, month - 1, date); 
} 
+0

感謝Valli。我在下面的Garrett的答案中提到過,因爲他鏈接的功能更小,並且使用我經常使用的日期格式 – pedalpete 2010-02-02 18:33:39

15

別T選用 「新的Date()」,因爲它需要輸入的日期字符串爲本地時間:

new Date('11/08/2010').getTime()-new Date('11/07/2010').getTime(); //90000000 
new Date('11/07/2010').getTime()-new Date('11/06/2010').getTime(); //86400000 

我們應該使用「NewDate() 」,它需要輸入爲GMT時間:

function NewDate(str) 
     {str=str.split('-'); 
      var date=new Date(); 
      date.setUTCFullYear(str[0], str[1]-1, str[2]); 
      date.setUTCHours(0, 0, 0, 0); 
      return date; 
     } 
NewDate('2010-11-07').toGMTString(); 
NewDate('2010-11-08').toGMTString(); 
1

這裏是我的方法:

var parseDate = function(dateArg) { 
    var dateValues = dateArg.split('-'); 
    var date = new Date(dateValues[0],dateValues[1],dateValues[2]); 
    return date.format("m/d/Y"); 
} 

與您所使用的分隔符替換('-')

2

下面是修復IE (v ['date']是逗號分隔日期字符串的行爲的代碼片段,例如,「2010,4,1」):

if($.browser.msie){ 
    $.lst = v['date'].split(','); 
    $.tmp = new Date(parseInt($.lst[0]),parseInt($.lst[1])-1,parseInt($.lst[2])); 
} else { 
    $.tmp = new Date(v['date']); 
} 

以前的做法沒有考慮到JS日期月份從零開始......

對不起,不解釋太多,我在工作和只是認爲這可能有幫助。

81

從MySQL日期時間/時間戳格式:

var dateStr="2011-08-03 09:15:11"; //returned from mysql timestamp/datetime field 
var a=dateStr.split(" "); 
var d=a[0].split("-"); 
var t=a[1].split(":"); 
var date = new Date(d[0],(d[1]-1),d[2],t[0],t[1],t[2]); 

我希望是有用的人。 在IE FF鉻

+1

不錯的一個!感謝分享+1 – 2012-02-06 21:35:38

+2

謝謝,正是我所需要的。 – Pascal 2012-11-19 15:00:40

+1

適用於Internet Explorer 8 – max4ever 2013-06-18 14:23:08

7

這裏的另一種方法,增加了一個方法將Date對象

用法:var d = (new Date()).parseISO8601("1971-12-15");

 
    /** 
    * Parses the ISO 8601 formated date into a date object, ISO 8601 is YYYY-MM-DD 
    * 
    * @param {String} date the date as a string eg 1971-12-15 
    * @returns {Date} Date object representing the date of the supplied string 
    */ 
    Date.prototype.parseISO8601 = function(date){ 
     var matches = date.match(/^\s*(\d{4})-(\d{2})-(\d{2})\s*$/); 

     if(matches){ 
      this.setFullYear(parseInt(matches[1]));  
      this.setMonth(parseInt(matches[2]) - 1);  
      this.setDate(parseInt(matches[3]));  
     } 

     return this; 
    }; 
+0

http://stackoverflow.com/review/suggested-edits/3261141 – Stano 2013-10-31 22:52:27

2

我一直保存在我的UTC時間日期。

這是我自己的功能,由我在此頁面中找到的不同功能組成。

它需要一個字符串作爲mysql日期時間格式(例如:2013-06-15 15:21:41)。使用正則表達式的檢查是可選的。您可以刪除此部分以提高性能。

該函數返回一個時間戳。

DATETIME被視爲UTC日期。小心:如果你期待本地日期時間,這個函數不適合你。

function datetimeToTimestamp(datetime) 
    { 
     var regDatetime = /^[0-9]{4}-(?:[0]?[0-9]{1}|10|11|12)-(?:[012]?[0-9]{1}|30|31)(?: (?:[01]?[0-9]{1}|20|21|22|23)(?::[0-5]?[0-9]{1})?(?::[0-5]?[0-9]{1})?)?$/; 
     if(regDatetime.test(datetime) === false) 
      throw("Wrong format for the param. `Y-m-d H:i:s` expected."); 

     var a=datetime.split(" "); 
     var d=a[0].split("-"); 
     var t=a[1].split(":"); 

     var date = new Date(); 
     date.setUTCFullYear(d[0],(d[1]-1),d[2]); 
     date.setUTCHours(t[0],t[1],t[2], 0); 

     return date.getTime(); 
    } 
0

您可以使用下面的代碼來解析ISO8601日期字符串:

function parseISO8601(d) { 
    var timestamp = d; 
    if (typeof (d) !== 'number') { 
     timestamp = Date.parse(d); 
    } 
    return new Date(timestamp); 
}; 
0

試試使用datepickergetDate功能。

$.datepicker.formatDate('yy-mm-dd',new Date(pField.datepicker("getDate"))); 
+0

請詳細說明你想要解釋的答案。 – 2016-07-18 06:17:12

相關問題