0

I am trying to calculate the days between 2 dates and it is working as far as I can tell but I keep getting stupidly high numbers which clearly isn't right, I have a feeling this is the way my dates are set out. my dates are set out as dd/mm/yyyy and this is the code I am using:

var diff = new Date(end_date - start_date);
var days = diff/1000/60/60/24;
console.log("diff=>"+days);

This is the question I used to get the answer: JavaScript date difference Days

When it writes to the console this is the result I get:

diff=>17301.95833332176
SynozeN Technologies
  • 1,337
  • 1
  • 14
  • 19
kieron oates
  • 115
  • 1
  • 2
  • 15
  • Can you show an actual example of it failing? Create a snippet? – StudioTime May 25 '17 at 14:02
  • Please show us exactly what your `start_date` and `end_date` look like. – Quiver May 25 '17 at 14:11
  • For the end date i am using `.datepicker("getDate")` to get the date in the format of dd/mm/yyyy and for the start date i am using a php function to get today's date `date("d/m/Y", mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")))` – kieron oates May 25 '17 at 14:21

3 Answers3

1

I have had a play with the code, although I have not used HTML, i set the vars statically below.

var end_date = new Date("May 25, 2017");
var start_date = new Date("May 23, 2017");
var diff = new Date(end_date - start_date);
var days = diff/1000/60/60/24;
console.log("diff=>"+days);

I have also checked it with a 3 value date format

var end_date = new Date(2017,4,25);
var start_date = new Date(2017,4,23);
var diff = new Date(end_date - start_date);
var days = diff/1000/60/60/24;
console.log("diff=>"+days);

I manage to get an output of 2. Which is what i expected. The code you supplied looks ok to me. Maybe look at the HTML to check that the values being passed are in the correct format.

Jquery datepicker may be of help to you here.

Kalacia
  • 76
  • 5
  • For the end date i am using `.datepicker("getDate")` to get the date in the format of dd/mm/yyyy and for the start date i am using a php function to get today's date `date("d/m/Y", mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")))` – kieron oates May 25 '17 at 14:21
  • 1
    Do you need to use the PHP? you could use the JS Date.now(); to pass todays date though. – Kalacia May 25 '17 at 14:26
  • it was something as simple as that, it was something wrong with the format of the php date that was messing it up, thanks for your help! switching it to date.now() fixed it – kieron oates May 25 '17 at 14:28
0

Easy solution, is to use countBtw

var { date } = require('aleppo')
//..
date.countBtw('all', date1, date2)
Jalal
  • 3,308
  • 4
  • 35
  • 43
0

You could also use moment: https://momentjs.com

var moment = require('moment');

var start_moment = moment(start_date);
var end_moment = moment(end_date);

var days = start_moment.diff(end_moment, 'days');
console.log("diff=>" + days);

You can also get weeks, months etc. with this method

bmpickford
  • 90
  • 1
  • 9