56

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

FinDev
  • 4,437
  • 6
  • 29
  • 29
  • does alert(Date("2010-08-17 12:09:36").getMonth()); work? I just pasted var temp = new Date("2010-08-17 12:09:36"); alert(temp); in an HTML page and it worked fine. – Zebi Aug 17 '10 at 18:32
  • Use new Date("2010-08-17T12:09:36") or new Date("2010-08-17T12:09:36Z") for UTC time. – Jack Feb 20 '14 at 21:16

10 Answers10

66

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"
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
Topera
  • 12,223
  • 15
  • 67
  • 104
  • Is there no other way to process the string without creating my own date parser? – FinDev Aug 17 '10 at 19:16
  • I don't know how do this using native js. But you can use a external parser, like datejs (http://www.datejs.com/) – Topera Aug 17 '10 at 19:37
  • 2
    Also in chrome and firefox new Date() works different. For example "yyyy-mm-dd hh:mm:ss" is suitable for chrome but not for firefox. – sunprophit Jul 01 '13 at 08:10
  • *"It accepts date in format "yyyy-mm-dd hh:mm:ss""* Maybe this was true 4 years ago, but no anymore today. `Date('2014-05-01 00:00:00')` simply returns the *current* date/time, in both Chrome and Firefox. – Felix Kling Feb 20 '14 at 05:51
  • 2
    @FelixKling, you forgot to call Date with the 'new' keyword. new Date('2014-05-01 00:00:00') does give you the correct May 1st date. – Jack Feb 20 '14 at 13:02
  • @Jack: You are right, it works in Chrome, but not in Firefox. However, I was *specifically* referring to `Date`, without `new`. If you have a look at the answer again, it claims that `Date()` (without `new`) accepts a date string in that format, but it doesn't. – Felix Kling Feb 20 '14 at 16:39
  • Oh, seems you are correct about FireFox. I guess that's understandable since that format is non-standard. Use a 'T' to designate the time (and optionally 'Z' for UTC time): "2014-05-01T00:00:00Z". I don't think commenter intended to imply that the date constructor should be called without new when specifying a dateString. – Jack Feb 20 '14 at 21:12
  • Also note that you can use other formats. According to MDN... `String value representing a date. The string should be in a format recognized by the Date.parse() method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601).` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date – Joel Kinzel Oct 17 '14 at 14:04
  • This answer is quite out of date now. When called as a function, [*Date*](http://www.ecma-international.org/ecma-262/6.0/#sec-date-value) accepts strings, numbers and objects. Also, it should never be passed a string (other than perhaps the [*format specified in ECMA-262*](http://www.ecma-international.org/ecma-262/6.0/#sec-date-time-string-format)) as the results are almost entirely implementation dependent (which was more so in 2010 with ECMA-262 ed 3 than now with ECMAScript 2015). – RobG Feb 17 '16 at 04:29
  • While some implementations may accept that format, it is not required to be supported by ECMA-262 up to ed 6 at least. Far better to use a 2 line parsing function. – RobG Feb 17 '16 at 06:07
39

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, "/"));
Skurpi
  • 1,000
  • 1
  • 12
  • 22
Daghall
  • 589
  • 6
  • 10
  • 1
    +1 : worked for me in IE5-11 and seems the simplest solution when converting an ISO-8601 style string date. – Yogi Feb 16 '15 at 17:56
  • No, don't do that. Far better to implement a 2 line function to manually parse the string (or use a library, but not really necessary). The language specification does note require browsers to parse **any** string other than ISO 8601 format, and some don't support that either. – RobG Feb 17 '16 at 06:05
6

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

Amol M Kulkarni
  • 21,143
  • 34
  • 120
  • 164
Vals
  • 279
  • 2
  • 7
4

I know this is old but by far the easier solution is to just use

var temp = new Date("2010-08-17T12:09:36");
TrippLamb
  • 1,422
  • 13
  • 24
  • This fails in Safari. – Union find Jun 14 '15 at 04:58
  • 3
    Just because it fails in Safari doesn't mean it isn't a correct use of JavaScript. I don't have Safari to test this either, but I don't know why something this ubiquitous would work in some browsers and not in others. In any event it definitely isn't deserving of a down vote. – TrippLamb Jun 18 '15 at 15:03
  • 1
    @TheComposer—welcome to the world of browser scripting. Until ES5, there was **no** string that browsers were required to parse by the standard. Some of those browsers are still in use. It is a certainty that at any point in time there are browsers in use that don't fully support the most recent standard (or even one a few years old), so you must program for the lowest common denominator of what browsers support, not strictly what the current specification states. – RobG Feb 17 '16 at 06:00
  • 1
    Parsing strings with the Date constructor is very widely recommended against, for good reasons (such as "browser X doesn't support that format"). – RobG Feb 17 '16 at 06:02
  • 1
    The OP never even mentions that he is programming in a browser. It works in Node, multiple mainstream browsers, and is used in examples in both W3 and Mozilla Documentation. So, I stand by my claim that while knowing that it fails in this or that is a good piece of information to note, it does properly answer the question within reasonable assumptions and is still not deserving of a down vote. – TrippLamb Feb 24 '16 at 19:12
  • Please share more details. What did you change and why? Please add all clarification to your answer by editing it, such that others can learn from it – Nico Haase Apr 17 '23 at 15:15
  • This is a 9 year old answer... Especially when the edit would just be saying because the format op was using wasn't correct because it was missing the single character difference. If a user can't process that difference, it is unlikely that an overly explained version of this answer will help them either. – TrippLamb Apr 28 '23 at 20:36
3

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
letronje
  • 9,002
  • 9
  • 45
  • 53
3

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
);
RobG
  • 142,382
  • 31
  • 172
  • 209
1

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();
sherkon18
  • 11
  • 1
  • No, don't pass strings to the Date constructor. Parsing of an ISO 8601 date requires 2 lines of code, do that instead. – RobG Feb 17 '16 at 06:04
1

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>
    
Mendi Barel
  • 3,350
  • 1
  • 23
  • 24
0

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?

LarsH
  • 27,481
  • 8
  • 94
  • 152
-2

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.

friesrf
  • 5
  • 1
  • What is the use of two `Date()` here when you can directly feed the string in the `Date` constructor. – Rajesh Paul Jan 06 '14 at 14:02
  • 1
    @friesrf Your answer is entirely wrong. Calling Date("2010-08-17 12:09:36") will always return the value of calling Date() without any parameters. So with above code snippet, you'll never get the parsed date object of malformed date string, instead a new date object that is equivalent to now. Code doesn't produce an error never means it is functionally correct. – M N Islam Shihan Jan 29 '14 at 21:12