How to parse a string into a date object at JavaScript (without using any 3d party) that is at dd-MM-yyyy HH:mm (all of them numbers) format?
Asked
Active
Viewed 1,016 times
1
-
possible duplicate of [Best JavaScript Date Parser & Formatter?](http://stackoverflow.com/questions/206790/best-javascript-date-parser-formatter) – Kirk Woll Mar 11 '11 at 19:02
-
possible duplicate of [How can I convert string to datetime with format specification in JavaScript?](http://stackoverflow.com/questions/476105/how-can-i-convert-string-to-datetime-with-format-specification-in-javascript) – Bertrand Marron Mar 11 '11 at 19:04
-
@Kirk Woll I couldn't find any answer at your link that handles my question without using any 3d party? – kamaci Mar 11 '11 at 19:06
-
@kamaci, you can't specify the date format with `Date.parse()`, so you would have to write your own parser. Or use a 3d party library/function. – Bertrand Marron Mar 11 '11 at 19:07
-
@kamaci, that is because there is no built-in support for extensive date parsing in javascript. – Kirk Woll Mar 11 '11 at 19:08
-
Is $.parseDate('dd-MM-yyyy HH:mm', dateVariable); OK with JQuery? – kamaci Mar 11 '11 at 19:09
2 Answers
3
var p = "04-22-1980 12:22".split(/-|\s+|:/);
// new Date(year, month, day [, hour, minute, second, millisecond ])
new Date(p[2], p[0] - 1, p[1], p[3], p[4]);
// => Tue Apr 22 1980 12:22:00 GMT-0500 (Central Daylight Time)

Wayne
- 59,728
- 15
- 131
- 126
0
DateJS is your friend: http://www.datejs.com/
It parses pretty much anything reasonable you throw at it:
// Convert text into Date
Date.parse('today');
Date.parse('t + 5 d'); // today + 5 days
Date.parse('next thursday');
Date.parse('February 20th 1973');
Date.parse('Thu, 1 July 2004 22:30:00');
It's not perfect, but it does a pretty good job.

Nicholas Carey
- 71,308
- 16
- 93
- 135