new Date支持的參數:
MDN:
new Date();
new Date(value);
new Date(dateString);
new Date(year, month, day, hour, minute, second, millisecond);
MSDN:
dateObj = new Date()
dateObj = new Date(dateVal)
dateObj = new Date(year, month, date[, hours[, minutes[, seconds[,ms]]]])
不過在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.
參考文章:
1、https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
2、https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
3、http://tools.ietf.org/html/rfc2822#page-14
4、http://www.w3.org/TR/NOTE-datetime
5、http://msdn.microsoft.com/en-us/library/ie/cd9w2te4(v=vs.94).aspx
6、http://msdn.microsoft.com/en-us/library/ie/ff743760(v=vs.94).aspx
7、http://www.php100.com/manual/Javascript/html/jsobjdate.htm