JavaScript Difference Between Two Dates In Years Example


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


Hello Friends,

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

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

Example : 1
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>JavaScript function to get time differences in years between two dates - MyWebtuts.com </title>
    </head>
    <body>
        <script type="text/javascript">
            function diff_years(dt2, dt1) 
            {
                var diff =(dt2.getTime() - dt1.getTime()) / 1000;
                diff /= (60 * 60 * 24);
                return Math.abs(Math.round(diff/365.25));
            }
            dt1 = new Date(2014,10,2);
            dt2 = new Date(2014,10,11);

            dt1 = new Date("June 13, 2014 08:11:00");
            dt2 = new Date("October 19, 2017 11:13:00");
            document.write(diff_years(dt1, dt2));
        </script>
    </body>
</html>
Output :
3
Example : 2
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>calculate difference between two dates in year javascript - MyWebtuts.com </title>
    </head>
    <body>
        <script type = "text/javascript">
            function cmp(dt1, dt2) 
            {
                var emp =(dt2.getTime() - dt1.getTime()) / 1000;
                emp /= (60 * 60 * 24);
                return Math.abs(Math.round(emp/365.25));
            }
            dt1 = new Date("2018-11-27");
            dt2 = new Date("2021-06-28");
     
            var cmd = cmp(dt1, dt2)
            document.write( "calculate difference between two dates in year javascript :- " + cmd ); 
        </script>  
    </body>
</html>
Output :
calculate difference between two dates in year javascript :- 3

It will help you...

Share: