new Date参数问题

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

原文地址:https://www.cnblogs.com/shinnyChen/p/3722487.html