Reputation: 6802
I have a string with a specific format which I am trying to convert to a Date object. I was hoping var dateObject = new Date(myString)
would be sufficient but it won't work. So I tried breaking up the string into smaller pieces, and that didn't work either.
var str = '2015-02-20 11:00';
var obj = new Date(str.substr(2, 4), str.substr(5, 7), str.substr(8, 10), str.substr(13, 15), str.substr(16, 18));
// Above code yields invalid date
How can I make a date object out of my string?
Upvotes: 0
Views: 102
Reputation:
Your format is quite close to the standard one, just replace the whitespace with T
:
var date = new Date(str.split(' ').join('T'));
http://es5.github.io/#x15.9.1.15
Just checked IE8. Doesn't work indeed...
Upvotes: 0
Reputation: 66304
Because you already have the units in the same order as the Date constructor takes them, you could do it this way..
var str = '2015-02-20 11:00',
args = str.split(/[ :-]/).map(Number);
args[1] = args[1] - 1; // fix months;
var d = new Date; // this and the next line are separated otherwise
Date.apply(d, args); // you end up with a String and not a Date
d; // Wed Mar 05 2014 14:13:47 GMT+0000 (GMT Standard Time)
Trying in the console of IE11 emulating IE9 works fine, too.
Upvotes: 0
Reputation: 3921
Change your line of code to this
var str = '2015-02-20 11:00';
var obj = new Date(str.substr(0, 4), str.substr(5, 2), str.substr(8, 2), str.substr(11, 2), str.substr(14, 2));
It will work.
You use the ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS
For example: new Date('2011-04-11')
or
new Date('2011-04-11T11:51:00')
Upvotes: 0
Reputation: 318182
Did you try just
var str = '2015-02-20 11:00';
var obj = new Date(str);
works for me -> http://jsfiddle.net/j5kaC/1/
If for some strange reason that doesn't work, split it up and pass it to the Date constructor in the appropriate places
var str = '2015-02-20 11:00';
var arr = str.split(' ');
var time = arr.pop().split(':')
var arr2 = arr.shift().split('-');
var date = new Date(arr2[0], arr2[1]-1, arr2[2], time.shift(), time.pop(), 0, 0);
console.log(date);
Upvotes: 5