Difference between Date(dateString) and new Date(dateString)

Viewed 108479

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().

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()?

10 Answers

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>
    

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.

Related