Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get difference in year where dates are in yyyy-mm-dd?

Tags:

javascript

i want to get the difference between two dates which are give in yyyy-mm-dd format difference should be in year.

        var ds='2002-09-23';
        var today_date = new Date();
        alert(today_date);
        Date.prototype.yyyymmdd = function() {
        var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
        var dd  = this.getDate().toString();
        var dt = yyyy +"-"+(mm[1]?mm:"0"+mm[0]) +"-"+ (dd[1]?dd:"0"+dd[0]);// padding
        var num_years = diff_date/31536000000;
        alert(num_years);
        if (num_years>18){
           alert (num_years);
        }else{
        alert ("i m not 18");
               }

please help me out.

like image 992
Manish Malviya Avatar asked Dec 08 '22 23:12

Manish Malviya


1 Answers

This is much shorter:

var yearsApart = new Date(new Date - new Date('2002-09-23')).getFullYear()-1970

… but be careful to take care of non UTC time zones by providing the correct datetime string!

like image 67
adius Avatar answered Feb 19 '23 00:02

adius