简体   繁体   中英

Javascript datetime string to Date object

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.

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

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

它只是简化版本:

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

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

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

should do the trick

使用parseExact方法

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

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