JavaScript Difference Between Two Dates In Months Example


Share:
Published By: Admin, Published On: Sep 11, 2021, Category: Javascript


Hello Friends,

Now let's see example of how to get difference between two dates in months example. We will use how to get difference between two dates in months in javascript. Here you will learn how to use javascript get difference between two dates in months.Let's get started with how to get difference between two dates in months in javascript.

Here i will give you many example how you can get difference between two dates in months javascript.

Example : 1
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>JavaScript Difference Between Two Dates in Months - MyWebtuts.com </title>
    </head>
    <body>
    <script type="text/javascript">
        function cmpdiff(dt2, dt1) 
        {
            var emp =(emp2.getTime() - emp1.getTime()) / 1000;
            emp /= (60 * 60 * 24 * 7 * 4);
            return Math.abs(Math.round(emp));
        }
        emp1 = new Date(2018,8,2);
        emp2 = new Date(2022,2,11);

        emp1 = new Date("June 12, 2018 08:11:00");
        emp2 = new Date("October 19, 2021 11:13:00");
        document.write(cmpdiff(emp1, emp2));
    </script>
    </body>
</html>
Output :
44
Example : 2
<!DOCTYPE html>
<html>
    <head>
        <title>JavaScript Difference Between Two Dates in Months - MyWebtuts.com </title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" crossorigin="anonymous"></script>
    </head>
    <body>
    <script type="text/javascript">
        var startDate = moment('02-01-2021', 'DD-MM-YYYY');
        var endDate = moment('02-05-2022', 'DD-MM-YYYY');
      
        var cmd = endDate.diff(startDate, 'months');
        document.write('Month:' + cmd);
    </script> 
    </body>
</html>
Output :
Month:16

It will help you...

Share: