Moment.js - two dates difference in number of days
Asked Answered
D

6

78

I get incorrect results when trying to find numeric difference between two dates:

var startDate = moment( $('[name="date-start"]').val(), "DD.MM.YYYY"), // $('[name="date-start"]').val() === "13.04.2016"
endDate       = moment( $('[name="date-end"]'  ).val(), "DD.MM.YYYY"); // $('[name="date-end"]').val() === "28.04.2016"

var diff = startDate.diff(endDate);

console.log( moment(diff).format('E') );

Between 13.04.2016 and 28.04.2016 I shouldn't get that difference is 3 or 2 days...

I've tried to multiple combinations:

  • swap startDate.diff(endDate) with endDate.diff(startDate)
  • format('E') with something I've come up searching the SO

Result: all the time I get that difference is 3 or 2 days.

What am I doing wrong?

Danas answered 13/4, 2016 at 13:57 Comment(0)
K
148

From the moment.js docs: format('E') stands for day of week. thus your diff is being computed on which day of the week, which has to be between 1 and 7.

From the moment.js docs again, here is what they suggest:

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1

Here is a JSFiddle for your particular case:

$('#test').click(function() {
  var startDate = moment("13.04.2016", "DD.MM.YYYY");
  var endDate = moment("28.04.2016", "DD.MM.YYYY");

  var result = 'Diff: ' + endDate.diff(startDate, 'days');

  $('#result').html(result);
});
#test {
  width: 100px;
  height: 100px;
  background: #ffb;
  padding: 10px;
  border: 2px solid #999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>

<div id='test'>Click Me!!!</div>
<div id='result'></div>
Kierkegaard answered 13/4, 2016 at 14:0 Comment(5)
ok, but how do I get that difference between these two dates are 15 days? Thanks for answerLanellelanette
Updated my answer... do check and let me know if it still doesn't workKierkegaard
Thanks for solution, but now I would have to add a lot of code to get that array since what I get from $('input[name="date-start"]').val() is "13.04.2016". Is there any solution that would work with my current date format?Lanellelanette
@Miloshio : No need to use it exactly as defined in the documentation. You can use your own Moment. I included a jsfiddle which should help clarify.Kierkegaard
@Miloshio : does the example help or are you still facing problems?Kierkegaard
F
10

Here's how you can get the comprehensive full fledge difference of two dates.

 function diffYMDHMS(date1, date2) {

    let years = date1.diff(date2, 'year');
    date2.add(years, 'years');

    let months = date1.diff(date2, 'months');
    date2.add(months, 'months');

    let days = date1.diff(date2, 'days');
    date2.add(days, 'days');

    let hours = date1.diff(date2, 'hours');
    date2.add(hours, 'hours');

    let minutes = date1.diff(date2, 'minutes');
    date2.add(minutes, 'minutes');

    let seconds = date1.diff(date2, 'seconds');

    console.log(years + ' years ' + months + ' months ' + days + ' days ' + hours + ' 
    hours ' + minutes + ' minutes ' + seconds + ' seconds'); 

    return { years, months, days, hours, minutes, seconds};
}
Flooring answered 13/12, 2018 at 11:3 Comment(0)
A
5

Use moment.js to find the difference between two dates in days.

Install moment.js using the following command,

npm install moment

Calculate the difference between two dates in days.

var moment = require('moment');

var date1 = moment("2022-10-30");
var date2 = moment("2022-12-30");
var days = date1.diff(date2, 'days') 
Alidaalidade answered 15/7, 2022 at 15:34 Comment(1)
I agreed, but your example may return days in the negative. The best way to use the second date after the first date. like var days = date2.diff(date1, 'days')Falgout
G
0

the diff method returns the difference in milliseconds. Instantiating moment(diff) isn't meaningful.

You can define a variable :

var dayInMilliseconds = 1000 * 60 * 60 * 24;

and then use it like so :

diff / dayInMilliseconds // --> 15

Edit

actually, this is built into the diff method, dubes' answer is better

Genipap answered 13/4, 2016 at 14:4 Comment(1)
This helped a lot, let me see if I'd go this wayLanellelanette
T
0
const FindDate = (date, allDate) => {
        
    // moment().diff only works on moment(). Make sure both date and elements in allDate array are in moment format
    let nearestDate = -1; 
    
    allDate.some(d => {
        const currentDate = moment(d)
        const difference = currentDate.diff(d); // Or d.diff(date) depending on what you're trying to find
        if(difference >= 0){
            nearestDate = d
        }
    });
    
    console.log(nearestDate)
}
Tournedos answered 7/2, 2020 at 18:11 Comment(0)
W
0

Calculate the differance in Seconds

var date1 = moment("2022-10-30");
var date2 = moment("2022-12-30");
var diff = date1.diff(date2, 'seconds') 

and then you can conver then in to hours and Minutes and seconds.

var mind = diff % (60 * 60);
const hours = Math.floor(diff / (60 * 60));
const minutes = Math.floor(mind / 60);
var seconds = Math.ceil(mind % 60);

Thanks

Wowser answered 13/4, 2023 at 5:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.