0

I know this question has been asked a thousand times, but im trying to get javascript to display me the days between two dates. I have seen this post:How do i get the number of days between two dates in javascript

From one of the comments I have used this code:

<input type="text" name="sod" class="startd" value="10/02/2016" />
<input type="text" name="dos" class="endd"  value="12/02/2016" />

  <script>
  function treatAsUTC(date) {
      var result = new Date(date);
      result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
      return result;
  }

  function daysBetween(startDate, endDate) {
      var millisecondsPerDay = 24 * 60 * 60 * 1000;
      return (treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay;
  }

  alert(daysBetween($('.startd').val(), $('.endd').val()));
  </script>

The reulst from the javascript give 61 days, but I want it to read as dd/mm/yyyy not mm/dd/yyyy as it currently is, so the result should be 2 days.

I have tried removing the treatAsUTC parts but it then desont give any answer at all.

  function daysBetween(startDate, endDate) {
      var millisecondsPerDay = 24 * 60 * 60 * 1000;
      return (endDate - startDate) / millisecondsPerDay;
  }

  alert(daysBetween($('.startd').val(), $('.endd').val()));

can any one help or guide me in the right direction?

Thanks in advance.

Ian

Community
  • 1
  • 1
snookian
  • 863
  • 6
  • 13
  • 35
  • 1
    So the issue is in date format. right? You can try `date.split("/").reverse().join("/")`. This will return date in `yyyy/mm/dd` – Rajesh Feb 09 '16 at 13:07
  • @Rajesh—which is a format that is very unreliable. There is no standard string format that is consistently parsed in all browsers, they must be manually parsed (a library can help but isn't necessary). Parsing any date format reliably is 2 lines of code, including validation. – RobG Feb 09 '16 at 13:17
  • Well, I didnt know that. In that case, it would be wise to split string and then create new Date object manually. In OP's case, `new Date(arr[2], arr[0]-1, arr[1])` – Rajesh Feb 09 '16 at 13:20
  • d/m/y isn't really "Europe" format, it's just a common format used outside the USA. There are many Europeans that use y-m-d format, m/d/y is peculiar to North America. – RobG Feb 09 '16 at 13:37

1 Answers1

1

The reulst from the javascript give 61 days, but I want it to read as dd/mm/yyyy not mm/dd/yyyy as it currently is, so the result should be 2 days.

So you just need to parse the date correctly. The original was:

function parseDate(str) {
    var mdy = str.split('/')
    return new Date(mdy[2], mdy[0]-1, mdy[1]);
}

Which parses a date in m/d/y format, so to support d/m/y, just change the last line to:

    return new Date(mdy[2], mdy[1]-1, mdy[0]);

Tidying up the code a bit, you might end up with something like:

// Parse a date in d/m/y format as UTC
function treatAsUTC(s) {
  var b = s.split(/\D/);
  return new Date(Date.UTC(b[2], b[1]-1, b[0]));
}

function daysBetween(startDate, endDate) {
  startDate = treatAsUTC(startDate);
  endDate = treatAsUTC(endDate);
  return (endDate - startDate) / 8.64e7;
}

function calcDiff() {
  document.querySelector('#result').value = 
     (daysBetween(document.querySelector('#sod').value,
      document.querySelector('#dos').value));
}
<input type="text" id="sod" class="startd" value="10/02/2016" />d/m/y
<input type="text" id="dos" class="endd"  value="12/02/2016" />d/m/y
<br>
<button onclick="calcDiff()">Calculate difference in days</button>
<input type="text" id="result" readonly>Days

But you don't actually need UTC, you can just round the result. If parsing dates, the milliseconds will only ever be out by the daylight saving change, rounding to the nearest whole day fixes that. But I guess it's nice using UTC as it doesn't need rounding.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • Nice, Thankyou! Im am bad at javascript. One more quick question, how do I just display that result rather than onClick – snookian Feb 09 '16 at 14:17
  • @snookian—just call *calcDiff* after the load event, or from a script below the inputs (like you did with *daysBetween* in the OP, I just thought you'd like to play with it). – RobG Feb 09 '16 at 20:59