Javascript Date(dateString) 和 new Date(dateString) 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3505693/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between Date(dateString) and new Date(dateString)
提问by Rishi
I have some code that tries to parse a date string.
我有一些代码试图解析日期字符串。
When I do alert(Date("2010-08-17 12:09:36"));It properly parses the date and everything works fine but I can't call the methods associated with Date, like getMonth().
当我做alert(Date("2010-08-17 12:09:36"));它正确解析日期和一切工作正常,但我不能把相关联的方法Date,像getMonth()。
When I try:
当我尝试:
var temp = new Date("2010-08-17 12:09:36");
alert(temp);
I get an "invalid date" error.
我收到“无效日期”错误。
Any ideas on how to parse "2010-08-17 12:09:36" with new Date()?
关于如何使用 new Date() 解析“2010-08-17 12:09:36”的任何想法?
回答by Topera
Date()
日期()
With this you call a function called Date(). It doesn't accept any arguments and returns a string representing the current date and time.
有了这个,你可以调用一个名为Date(). 它不接受任何参数并返回一个表示当前日期和时间的字符串。
new Date()
新日期()
With this you're creating a new instance of Date.
有了这个,您将创建一个新的 Date 实例。
You can use only the following constructors:
您只能使用以下构造函数:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
So, use 2010-08-17 12:09:36as parameter to constructor is not allowed.
因此,2010-08-17 12:09:36不允许用作构造函数的参数。
See w3schools.
EDIT: new Date(dateString)uses one of these formats:
编辑:new Date(dateString)使用以下格式之一:
- "October 13, 1975 11:13:00"
- "October 13, 1975 11:13"
- "October 13, 1975"
- “1975 年 10 月 13 日 11:13:00”
- “1975 年 10 月 13 日 11:13”
- “1975 年 10 月 13 日”
回答by Daghall
The following format works in allbrowsers:
以下格式适用于所有浏览器:
new Date("2010/08/17 12:09:36");
So, to make a yyyy-mm-dd hh:mm:ssformatted date string fully browser compatible you would have to replace dashes with slashes:
因此,要使yyyy-mm-dd hh:mm:ss格式化的日期字符串与浏览器完全兼容,您必须用斜杠替换破折号:
var dateString = "2010-08-17 12:09:36";
new Date(dateString.replace(/-/g, "/"));
回答by The Composer
I know this is old but by far the easier solution is to just use
我知道这是旧的,但到目前为止更简单的解决方案是使用
var temp = new Date("2010-08-17T12:09:36");
回答by Vals
The difference is the fact (if I recall from the ECMA documentation) is that Date("xx")does not create (in a sense) a new date object (in fact it is equivalent to calling (new Date("xx").toString()). While new Date("xx")will actually create a new date object.
不同之处在于(如果我从 ECMA 文档中回忆)Date("xx")它不会创建(在某种意义上)一个新的日期对象(实际上它相当于调用 ( new Date("xx").toString())。而new Date("xx")实际上会创建一个新的日期对象。
For More Information:
想要查询更多的信息:
Look at 15.9.2 of http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf
查看http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf 的15.9.2
回答by RobG
Any ideas on how to parse "2010-08-17 12:09:36" with new Date()?
关于如何使用 new Date() 解析“2010-08-17 12:09:36”的任何想法?
Until ES5, there was no string format that browsers were required to support, though there are a number that are widely supported. However browser support is unreliable an inconsistent, e.g. some will allow out of bounds values and others wont, some support certain formats and others don't, etc.
在 ES5 之前,没有要求浏览器支持的字符串格式,尽管有一些被广泛支持的数字。然而,浏览器支持是不可靠和不一致的,例如有些会允许越界值,有些则不会,有些支持某些格式,有些则不支持,等等。
ES5 introduced support for some ISO 8601 formats, however the OP is not compliant with ISO 8601 and not all browsers in use support it anyway.
ES5 引入了对某些 ISO 8601 格式的支持,但是 OP 不符合 ISO 8601 并且并非所有使用的浏览器都支持它。
The only reliable way is to use a small parsing function. The following parses the format in the OP and also validates the values.
唯一可靠的方法是使用一个小的解析函数。下面解析 OP 中的格式并验证值。
/* Parse date string in format yyyy-mm-dd hh:mm:ss
** If string contains out of bounds values, an invalid date is returned
** 
** @param {string} s - string to parse, e.g. "2010-08-17 12:09:36"
**                     treated as "local" date and time
** @returns {Date}   - Date instance created from parsed string
*/
function parseDateString(s) {
  var b = s.split(/\D/);
  var d = new Date(b[0], --b[1], b[2], b[3], b[4], b[5]);
  return d && d.getMonth() == b[1] && d.getHours() == b[3] &&
         d.getMinutes() == b[4]? d : new Date(NaN);
}
  
document.write(
  parseDateString('2010-08-17 12:09:36') + '<br>' +  // Valid values
  parseDateString('2010-08-45 12:09:36')             // Out of bounds date
);回答by letronje
Correct ways to use Date : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
使用日期的正确方法:https: //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
Also, the following piece of code shows how, with a single definition of the function "Animal", it can be a) called directly and b) instantiated by treating it as a constructor function
此外,以下代码显示了如何使用函数“Animal”的单一定义,a) 直接调用和 b) 通过将其视为构造函数来实例化
function Animal(){
    this.abc = 1;
    return 1234; 
}
var x = new Animal();
var y = Animal();
console.log(x); //prints object containing property abc set to value 1
console.log(y); // prints 1234
回答by LarsH
You're not getting an "invalid date" error. Rather, the value of temp is "Invalid Date".
您没有收到“无效日期”错误。相反,temp 的值是“无效日期”。
Is your date string in a valid format? If you're using Firefox, check Date.parse
您的日期字符串格式是否有效?如果您使用 Firefox,请检查Date.parse
In Firefox javascript console:
在 Firefox javascript 控制台中:
>>> Date.parse("2010-08-17 12:09:36");
NaN
>>> Date.parse("Aug 9, 1995")
807944400000
I would try a different date string format.
我会尝试不同的日期字符串格式。
Zebi, are you using Internet Explorer?
Zebi,您使用的是 Internet Explorer 吗?
回答by sherkon18
I was having the same issue using an API call which responded in ISO 8601 format. Working in Chrome this worked: `
我在使用以 ISO 8601 格式响应的 API 调用时遇到了同样的问题。在 Chrome 中工作这有效:`
// date variable from an api all in ISO 8601 format yyyy-mm-dd hh:mm:ss
  var date = oDate['events']['event'][0]['start_time'];
  var eventDate = new Date();
  var outputDate = eventDate.toDateString();
`
`
but this didn't work with firefox.
但这不适用于 Firefox。
Above answer helped me format it correctly for firefox:
上面的答案帮助我为 Firefox 正确格式化:
 // date variable from an api all in ISO 8601 format yyyy-mm-dd hh:mm:ss
 var date = oDate['events']['event'][0]['start_time'];
 var eventDate = new Date(date.replace(/-/g,"/");
 var outputDate = eventDate.toDateString();
回答by friesrf
I recently ran into this as well and this was a helpful post. I took the above Topera a step further and this works for me in both chrome and firefox:
我最近也遇到了这个问题,这是一个有用的帖子。我把上面的 Topera 更进一步,这对我来说在 chrome 和 firefox 中都适用:
var temp = new Date(  Date("2010-08-17 12:09:36")   );
alert(temp);
the internal call to Date()returns a string that  new Date()can parse.
内部调用Date()返回一个new Date()可以解析的字符串  。

