3

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?

zanzoken
  • 787
  • 4
  • 12
  • 18
  • when formatted as `2.13.2015` it works – DLeh Feb 25 '15 at 13:35
  • But this would be not a valid german date. Because the second number represents the month. – zanzoken Feb 25 '15 at 13:35
  • You should [read this document](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse). – Sverri M. Olsen Feb 25 '15 at 13:36
  • 1
    similar question http://stackoverflow.com/questions/6059649/how-to-convert-american-date-format-to-european – DLeh Feb 25 '15 at 13:36
  • 2
    same question http://stackoverflow.com/questions/3257460/new-date-is-working-in-chrome-but-not-firefox. Use [moment.js](http://momentjs.com/) to parse custom dates. – dusky Feb 25 '15 at 13:37
  • could you describe how to do it with moment.js? – zanzoken Feb 25 '15 at 13:40
  • 1
    @zanzoken read the [docs](http://momentjs.com/docs/#/parsing/string-format/). `moment("13.02.2015 12:55", "DD.MM.YYYY HH:mm").toDate();` – dusky Feb 25 '15 at 13:46

2 Answers2

7

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.

Remigius Stalder
  • 1,921
  • 2
  • 26
  • 31
-1

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'));
hanshenrik
  • 19,904
  • 4
  • 43
  • 89