-1

hi could you please tell me how to find difference of dates using moments js? here is my code

https://jsfiddle.net/FLhpq/6082/

secondDate "2019-12-01"  // formate YYYY-MM-DD;
var day = moment().format('YYYY-MM-DD');
// difference of secondDate - date
alert('day'+secondDate - day)

Can we calculate the difference of years between two dates

expected output

3

user944513
  • 12,247
  • 49
  • 168
  • 318
  • there is a method called `diff()` – Satpal Sep 14 '16 at 10:08
  • I need differnce in year as example it should give `3` – user944513 Sep 14 '16 at 10:08
  • Possible duplicate of [JavaScript : How to Calculate number of days between two dates using javascript](http://stackoverflow.com/questions/9129928/javascript-how-to-calculate-number-of-days-between-two-dates-using-javascript) – Rajesh Sep 14 '16 at 10:14

4 Answers4

6

You can leverage on various methods i.e. diff(), asYears()

var firstDate = moment("2013-12-01", 'YYYY-MM-DD'); //Create date using string-format constructor
var secondDate = moment("2016-12-01", 'YYYY-MM-DD');
var duration = moment.duration(secondDate.diff(firstDate));
var years = duration.asYears();
console.log(years)
console.log(Math.round(years))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>
Satpal
  • 132,252
  • 13
  • 159
  • 168
2
var a = moment([2015, 11, 29]);
var b = moment([2007, 06, 27]);

var years = a.diff(b, 'year');

console.log(years + ' years);
Techidiot
  • 1,921
  • 1
  • 15
  • 28
0
<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.js"></script>
    <script>
        var a = moment("2016-11-04","YYYY-MM-DD");
        var b = moment("2000-11-04","YYYY-MM-DD");
        alert(a.diff(b, 'years')+" Year");
    </script>
</head>

Ketav
  • 760
  • 1
  • 8
  • 27
0
let firstDate = moment("11/07/2023","DD/MM/YYYY")
let today = moment(new Date());
let diff1 = firstDate.diff(today, 'days'); //for days
let diffYears = firstDate.diff(today, 'years'); //for years
console.log(diff1). //1
Mehdi Dehghani
  • 10,970
  • 6
  • 59
  • 64
devbiswasnegi
  • 280
  • 2
  • 5