Javascript datetime string for a Date object

I am debugging a small application with some functionality that will only work in Chrome. The problem is the datepeck, where you select the date and time, and the datepicker combines it into a datetime string.

In any case, the line looks like this: 2012-10-20 00:00 .

However, the javascript that uses it simply takes a string and initializes the object as follows: new Date('2012-10-20 00:00');

This results in an invalid date in Firefox, IE, and probably all browsers except Chrome. I need to tell how best to convert this datestring to a Date object in javascript. I have jQuery enabled.

Thank you for the wisdom of your sage and the best wisdom.

+4
source share
4 answers

If the format of the string always matches the state, then split the string and use bits, for example:

 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]); 
+14
source

This is just a simplified version:

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

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

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

gotta do the trick

+1
source

use parseExact method

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

Source: https://habr.com/ru/post/1440515/


All Articles