-3

How can I count the days between two dates in javascript? (without years only month and day for every years)

for example: Mai 6 (Without 2017) to Nov 7 (Without 2017) DAY:1, DAY:2, DAY:3..... And Nov 8 (Without 2017) to Mai 5 Next year (Without 2018) DAY:1, DAY:2, DAY:3..... I Have thish code but calculating the days only for this year and not from November 8 to next year Mai 5

  • 2
    If you don’t have the year, how do you decide how many days are in February? – Ry- Nov 20 '17 at 22:35

1 Answers1

-1
var day=1000*60*60*24;
var d1 = Date.parse('Jan 1');
var d2 = Date.parse('Jun 30');

var diff = d2 - d1;
Math.round(diff/day)

You were looking for the Date.parse function.

Take a look here at how it will be handled without a year being passed in. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

EDIT:

Here is a function that will append the current year and parse the dates. This is not code that should ever make it into production because the slightest change in the format of the date will break it. But to save face for the wrong solution I proposed try using this:

function getDays(strDay1, strDay2){
  var day=1000*60*60*24;

  strDay1 = strDay1 + ' ' + (new Date().getFullYear());
  strDay2 = strDay2 + ' ' + (new Date().getFullYear());

  var d1 = Date.parse(strDay1);
  var d2 = Date.parse(strDay2);

  var diff = d2 - d1;
  return Math.round(diff/day)
}

alert(getDays('Jan 1', 'Jun 30'));
  • `console.log(Date.parse('Jan 1'));` returns NaN in firefox – charlietfl Nov 20 '17 at 22:39
  • @charlietfl hmm, in Chrome it worked perfectly fine. guess that throws this solution out the window. – Adam Harris Nov 20 '17 at 22:40
  • Some browsers are less picky about date formats but if it doesn't work cross browser then it isn't ready for production (or as an answer) – charlietfl Nov 20 '17 at 22:41
  • @charlietfl I added in a super hacky approach but it should work as long as his date format doesn't change and using the current year is ok. I agree with you though, code like this shouldn't make it into production. – Adam Harris Nov 20 '17 at 22:53
  • Parsing of non–standard strings is implementation dependent (as you've discovered). Just don't do it. – RobG Nov 21 '17 at 02:38