2

Why is the first date invalid? I don't understand.

https://jsfiddle.net/r4dgjdn6/1/

$(document).ready(function() {

  alert(new Date('19.12.2016 14:00'));
  alert(new Date('12.12.2016 14:00'));

});

I want to calculate date difference but i keep getting the Invalid Date error.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
lewis4u
  • 14,256
  • 18
  • 107
  • 148

2 Answers2

3

You can use the library http://momentjs.com/ and use it like this:

var a = moment('19.12.2016 14:00', 'DD.MM.YYYY mm:ss');
var b = moment('12.12.2016 14:00', 'DD.MM.YYYY mm:ss');

//to calculate the diff
a.diff(b);
la3roug
  • 186
  • 1
  • 7
2

because the 'date' constructor can get specific "date format" as parameters

for example :

alert(new Date('Mon Dec 19 2016 14:00:00'));

take a look at this :

http://www.w3schools.com/js/js_dates.asp

EDIT:

if it is always in this format you can use this "quick" code to parse your string into the right format:

var inputString = '19.12.2016 14:00';
var tmpArray = inputString.split('.');
var result = tmpArray[1] + "-" + tmpArray[0] + "-" + tmpArray[2].split(' ')[0] + " " + tmpArray[2].split(' ')[1];
alert(new Date(result));
Developer
  • 460
  • 4
  • 17
  • and for thr difference between dates take a look at that : http://stackoverflow.com/questions/7763327/how-to-calculate-date-difference-in-javascript – Developer Dec 19 '16 at 14:43
  • ok and how can i parse the date from my input field if it's value is just like in my question `19.12.2016 14:00` – lewis4u Dec 19 '16 at 14:43
  • moment.js is my answer – lewis4u Dec 19 '16 at 14:46
  • gave you quick no thinking code for your problem, of course its not generic its only for your case only :) – Developer Dec 19 '16 at 14:56
  • 1
    if you have libary of course its better, but next time mentiond it in your question that you dont mind using libaries ;) – Developer Dec 19 '16 at 15:01
  • why it doesn't work again even with the library?? https://jsfiddle.net/pxxLzdvf/2/ – lewis4u Dec 19 '16 at 15:12
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/130964/discussion-between-lewis4u-and-oriel-f). – lewis4u Dec 19 '16 at 15:15
  • Please don't reference w3schools, the site is full of bad advice and errors. Please use ECMA-262 or MDN. – RobG Dec 21 '16 at 04:42