Javascript / jQuery / Moment.js calculate the number of days between two dates

I have downloaded games and reading loads, and still spent about 3 hours on this. I can’t believe it is so complicated.

I have a Javascript / JQuery application, I have the moment.js plugin installed. I am writing a POS application and I need to calculate the difference in days between two dates, so I can warn the user that the returned item may be too old to return.

I found this code in JS that looks good and seems to be a popular way to do this, although I just couldn't get it to work

var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2008,01,12);
var secondDate = new Date(2008,01,22);

var diffDays = Math.round(Math.abs((firstDate.getTime() -  secondDate.getTime())/(oneDay)));

I also tried this with Moment.js, which again looks very neat

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
var x = a.diff(b);

. "oDate.diff ", ...

todaysDate = moment(new Date()).format('YYYY, MM, DD');
oDate = moment(result.Order.created).format('YYYY, MM, DD');
var diffDays = oDate.diff(todaysDate, 'days');

, oDate. , .

. , todaysDate oDate console.log,  todaysDate - 2016, 09, 14  oDate - 2016, 09, 12

?

+4
4

, .,.once , . format .

todaysDate = moment(new Date());
oDate = moment(result.Order.created);
var diffDays = oDate.diff(todaysDate, 'days');
+4

unix (moment.unix()), moment.duration(),

+2

- ?

var startDate = new Date(2008, 01, 12);
var endDate = new Date(2008, 01, 22);
var duration = moment.duration(endDate.diff(startDate));
var diffDays = duration.asDays();

Here I use moment.duration()and diff()to get the interval between two dates, and then asDays()to get the result in days ...

+1
source

You can try the following:

function showDays(firstDate,secondDate){



              var startDay = new Date(firstDate);
              var endDay = new Date(secondDate);
              var millisecondsPerDay = 1000 * 60 * 60 * 24;

              var millisBetween = startDay.getTime() - endDay.getTime();
              var days = millisBetween / millisecondsPerDay;

              // Round down.
              alert( Math.floor(days));

          }
0
source

Source: https://habr.com/ru/post/1654554/


All Articles