zanzoken
zanzoken

Reputation: 877

Javascript Date String returns invalid Date

I am trying to convert a date string into a date object within javascript. My date has the following format:

"13.02.2015 12:55"

My current approach was:

var d = new Date("13.02.2015 12:55");

But this didnt work and always returns invalid date. If I enter a date as "12.02.2015 12:55" it works in chrome but not in firefox. I guess this is because he thinks the first part is the month, but in germany this is not the case.

How can I get this to work?

Upvotes: 4

Views: 18384

Answers (2)

Remigius Stalder
Remigius Stalder

Reputation: 2170

use moment.js:

var date = moment("13.02.2015 12:55", "DD.MM.YYYY HH.mm").toDate();

Update 2022-05-28:

Meanwhile the project status of moment.js has changed. Therefore I strongly suggest to read https://momentjs.com/docs/#/-project-status/ and observe the recommendations.

Upvotes: 7

hanshenrik
hanshenrik

Reputation: 21465

ISO 8601

try the ISO 8601 format, or better yet, read this http://www.ecma-international.org/ecma-262/5.1/#sec-15.9

Edit: if you have no other choice than to get it in that format though, i guess you'll need something like this:

function DDMMYYYY_HHMMtoYYYYMMDD_HHMM($DDMMYYYY_HHMM) {
  var $ret = '';
  var $foo = $DDMMYYYY_HHMM.split('.');
  var $DD = $foo[0];
  var $MM = $foo[1];
  var $YYYY = $foo[2].split(' ') [0].trim();
  var $HH = $foo[2].split(' ') [1].split(':') [0].trim();
  var $MMM = $foo[2].split(' ') [1].split(':') [1].trim();
  return $YYYY + '-' + $MM + '-' + $DD + ' ' + $HH + ':' + $MMM;
}
var d=new Date(DDMMYYYY_HHMMtoYYYYMMDD_HHMM('13.02.2015 12:55'));

Upvotes: -1

Related Questions