9

I am debugging a small application with some functionality which would only run in Chrome. The problem lies in a datepicker where you choose a date and time and the datepicker concaternates it into a datetime-string.

Anyway the string looks like this: 2012-10-20 00:00.

However, the javascript that uses it now just takes the string and initialize an object with it like this: new Date('2012-10-20 00:00');

This is resulting in an invalid date in Firefox, IE and probably all browsers but Chrome. I need advise in how I best could transform this datestring to a Date object in javascript. I have jQuery enabled.

Thanks for your sage advise and better wisdom.

4 Answers 4

19

If the string format is always as you state, then split the string and use the bits, e.g.:

var s = '2012-10-20 00:00';
var bits = s.split(/\D/);
var date = new Date(bits[0], --bits[1], bits[2], bits[3], bits[4]);
Sign up to request clarification or add additional context in comments.

3 Comments

isn't it possible to use the parse method in javascript? var m = Date.parse('2012-10-10 00:00'); d = new Date(m); ?
Ignore my comment, just tried it. Thanks for your answer, beautiful code.
ES5 includes a date time string format for Date.parse but not all browsers support it, there wasn't one in ECMA-262 ed 3. Safer just to parse it yourself.
6

It's just the simplify version:

 var newDate = new Date('2015-04-07 01:00:00'.split(' ')[0]);

Comments

1

if str = '2012-10-20 00:00'

new Date(str.split(' ')[0].split('-').join(',') + ',' + str.split(' ')[1].
split('-').join(','))

should do the trick

Comments

-3

use parseExact method

var date = new Date.parseExact(dateString, "yyyy-mm-dd hh-mm");

4 Comments

Parse method do not work since it's the same format on the datestring. The parseExact is from Date.js as far as I can find.
No need to introduce a new framework on an important application if you're just going to use it for this single thing. But yeah, no harm to use it as long as you use it from the beginning or if you really need it.
If you're going to reference external libraries, make sure you include a reference, or at least a note saying that you're using an external library.
no, it doesn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.