简体   繁体   中英

How can I convert this string to a javascript Date object?

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

JS-Fiddle Example

How can I make a date object out of my string?

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);

FIDDLE

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')

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM