4

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?

7
  • when formatted as 2.13.2015 it works Commented Feb 25, 2015 at 13:35
  • 1
    But this would be not a valid german date. Because the second number represents the month. Commented Feb 25, 2015 at 13:35
  • 1
    similar question stackoverflow.com/questions/6059649/… Commented Feb 25, 2015 at 13:36
  • 2
    same question stackoverflow.com/questions/3257460/…. Use moment.js to parse custom dates. Commented Feb 25, 2015 at 13:37
  • 1
    @zanzoken read the docs. moment("13.02.2015 12:55", "DD.MM.YYYY HH:mm").toDate(); Commented Feb 25, 2015 at 13:46

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

nice library! could be handy~
the javascript-date-swiss-army-knife, so to say.
-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'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.