Difference between Date(dateString) and new Date(dateString)
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 as开发者_如何学编程sociated with Date
, like 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()?
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.
new Date()
With this you're creating a new instance of 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:36
as parameter to constructor is not allowed.
See w3schools.
EDIT: new Date(dateString)
uses one of these formats:
- "October 13, 1975 11:13:00"
- "October 13, 1975 11:13"
- "October 13, 1975"
The following format works in all browsers:
new Date("2010/08/17 12:09:36");
So, to make a yyyy-mm-dd hh:mm:ss
formatted date string fully browser compatible you would have to replace dashes with slashes:
var dateString = "2010-08-17 12:09:36";
new Date(dateString.replace(/-/g, "/"));
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.
For More Information:
Look at 15.9.2 of http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf
I know this is old but by far the easier solution is to just use
var temp = new Date("2010-08-17T12:09:36");
Correct ways to use 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
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
Any ideas on how to parse "2010-08-17 12:09:36" with new Date()?
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 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.
The only reliable way is to use a small parsing function. The following parses the format in the OP and also validates the values.
/* 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
);
I was having the same issue using an API call which responded in ISO 8601 format. Working in Chrome this worked: `
// 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.
Above answer helped me format it correctly for 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();
You can also create single Date
object and update it using the static function Date.now()
:
<!doctype html>
<html> <head></head>
<body>
<h1 id="datetime"></h1>
<script>
elem_datetime = document.getElementById('datetime');
var date = new Date();
function sometimer()
{
setTimeout(sometimer, 1*1000); // wait 1 second and call again
date.setTime(Date.now());
elem_datetime.innerHTML = date.toDateString() + ' ' + date.toLocaleTimeString();
}
sometimer();
</script>
</body>
</html>
You're not getting an "invalid date" error. Rather, the value of temp is "Invalid Date".
Is your date string in a valid format? If you're using Firefox, check Date.parse
In Firefox javascript console:
>>> 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?
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:
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.
精彩评论