new Date參數問題

new Date支持的參數:javascript

MDN:php

  new Date();html

  new Date(value);java

  new Date(dateString);windows

  new Date(year, month, day, hour, minute, second, millisecond);ui

MSDN:spa

dateObj = new Date()code

dateObj = new Date(dateVal)orm

dateObj = new Date(year, month, date[, hours[, minutes[, seconds[,ms]]]]) htm

    不過在MSDN中把dateVal當作了MDN中參數爲value和dateString的合集。其實是同樣的。

 

    對於無參數和多參數的使用方法除了month參數是從0開始計算以外沒有什麼特殊用法。

    若是參數爲數字時表明從1970年1月1日算起的毫秒數:Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch)。最麻煩,可是使用起來也是最方便的字符串參數,在MDN中:

The string should be in a format recognized by theDate.parse() method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601).

在MSDN中:

dateVal is parsed according to the rules in Date and Time Strings (JavaScript). The dateVal argument can also be a VT_DATE value as returned from some ActiveX objects.

 

一句話來講,就是對於經過JS Date對象以及相關方法(UTC、ISO、GMT等)生成的各類字符串均可以解析。除此以外,經常使用的使用方法以下:

/*須要注意:月份此時從1開始計算*/
new Date("2014-04-11"); // Fri Apr 11 2014 08:00:00 GMT+0800 (中國標準時間)

注:該方式不推薦,由於在windows下的safari 5及如下版本不能正確解析,會返回NaN。而在Mac下的Safari則沒有此問題。不過若是忽略安裝Safari的windows用戶,這個方法也不錯。

 

通常咱們可能使用new Date(YYYY,MM,DD)或者set方法來建立對象,不過經過set方法在某些特殊日期下會出錯:

/*bad!*/

var date = new Date(2014,2,30); // Fri Mar 30 2014 00:00:00 GMT+0800 (中國標準時間) 
date.setMonth(1); // Fri Mar 2 2014 00:00:00 GMT+0800 (中國標準時間) 
date.setDate(28); // Fri Mar 28 2014 00:00:00 GMT+0800 (中國標準時間) 

var date = new Date(2014,1,28);  // Fri Feb 28 2014 00:00:00 GMT+0800 (中國標準時間) 
date.setDate(30); // Sun Mar 02 2014 00:00:00 GMT+0800 (中國標準時間) 
date.setMonth(3); // Wed Apr 02 2014 00:00:00 GMT+0800 (中國標準時間) 


/*better!*/

var dateNew = new Date(2014,1,28); // Fri Feb 28 2014 00:00:00 GMT+0800 (中國標準時間)
var dateNew2 = new Date(2014,3,30); // Wed Apr 30 2014 00:00:00 GMT+0800 (中國標準時間)

 

PS: ISO Date Format is not supported in Internet Explorer 8 standards mode and Quirks mode.

 

 

參考文章:

一、https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

二、https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

三、http://tools.ietf.org/html/rfc2822#page-14

四、http://www.w3.org/TR/NOTE-datetime

五、http://msdn.microsoft.com/en-us/library/ie/cd9w2te4(v=vs.94).aspx

六、http://msdn.microsoft.com/en-us/library/ie/ff743760(v=vs.94).aspx

七、http://www.php100.com/manual/Javascript/html/jsobjdate.htm

相關文章
相關標籤/搜索