Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript中以年、月、日为单位的两个日期之间的差异_Javascript_Date_Datediff - Fatal编程技术网

JavaScript中以年、月、日为单位的两个日期之间的差异

JavaScript中以年、月、日为单位的两个日期之间的差异,javascript,date,datediff,Javascript,Date,Datediff,我已经搜索了4个小时了,还没有找到一个解决方案来获得JavaScript中两个日期(年、月和日)之间的差异,比如:2010年4月10日是3年前,x月和y日前 有很多解决方案,但它们只提供了日、月或年的格式差异,或者它们不正确(意味着不考虑一个月或闰年的实际天数,等等)。真的有那么难吗 我看了一下: ->只能输出年、月或日的差值 www.stackoverflow.com->搜索功能 在php中很容易,但不幸的是,我只能在该项目上使用客户端脚本。任何能够做到这一点的库或框架也可以 以下是

我已经搜索了4个小时了,还没有找到一个解决方案来获得JavaScript中两个日期(年、月和日)之间的差异,比如:2010年4月10日是3年前,x月和y日前

有很多解决方案,但它们只提供了日、月或年的格式差异,或者它们不正确(意味着不考虑一个月或闰年的实际天数,等等)。真的有那么难吗

我看了一下:

  • ->只能输出年、月或日的差值
  • www.stackoverflow.com->搜索功能
在php中很容易,但不幸的是,我只能在该项目上使用客户端脚本。任何能够做到这一点的库或框架也可以

以下是日期差异的预期输出列表:

//Expected output should be: "1 year, 5 months".
diffDate(new Date('2014-05-10'), new Date('2015-10-10'));

//Expected output should be: "1 year, 4 months, 29 days".
diffDate(new Date('2014-05-10'), new Date('2015-10-09'));

//Expected output should be: "1 year, 3 months, 30 days".
diffDate(new Date('2014-05-10'), new Date('2015-09-09'));

//Expected output should be: "9 months, 27 days".
diffDate(new Date('2014-05-10'), new Date('2015-03-09'));

//Expected output should be: "1 year, 9 months, 28 days".
diffDate(new Date('2014-05-10'), new Date('2016-03-09'));

//Expected output should be: "1 year, 10 months, 1 days".
diffDate(new Date('2014-05-10'), new Date('2016-03-11'));
我会亲自使用,真的很方便。具体地说,看看time.js文件:

一些数学问题已经解决了

在Javascript中,您可以将一个日期对象与另一个日期对象相减,得到它们之间的差值,单位为毫秒。从该结果中,您可以提取所需的其他部分(天、月等)

例如:

var a = new Date(2010, 10, 1);
var b = new Date(2010, 9, 1);

var c = a - b; // c equals 2674800000,
               // the amount of milisseconds between September 1, 2010
               // and August 1, 2010.
现在你可以得到你想要的任何零件。例如,两个日期之间经过了多少天:

var days = (a - b) / (60 * 60 * 24 * 1000);
// 60 * 60 * 24 * 1000 is the amount of milisseconds in a day.
// the variable days now equals 30.958333333333332.

差不多31天了。然后,您可以将30天的时间四舍五入,并使用剩余的时间来计算小时数、分钟数等。

您需要多精确?如果您确实需要考虑普通年份和闰年,以及月与月之间的天数差,那么您必须编写更高级的内容,但对于基本和粗略的计算,这应该可以做到:

today = new Date()
past = new Date(2010,05,01) // remember this is equivalent to 06 01 2010
//dates in js are counted from 0, so 05 is june

function calcDate(date1,date2) {
    var diff = Math.floor(date1.getTime() - date2.getTime());
    var day = 1000 * 60 * 60 * 24;

    var days = Math.floor(diff/day);
    var months = Math.floor(days/31);
    var years = Math.floor(months/12);

    var message = date2.toDateString();
    message += " was "
    message += days + " days " 
    message += months + " months "
    message += years + " years ago \n"

    return message
    }


a = calcDate(today,past)
console.log(a) // returns Tue Jun 01 2010 was 1143 days 36 months 3 years ago
请记住,这是不精确的,为了精确计算日期,必须有一个日历,知道一年是否是闰年,而且我计算月数的方法只是近似的


但是你可以很容易地改进它

为了方便快捷,我不久前写了这个函数。它以良好的格式返回两个日期之间的差异。可以随意使用它(在webkit上测试)

/**
*用于打印日期差异的函数。
* 
*@param{Date}fromDate:有效的开始日期
*@param{Date}toDate:结束日期。可以为null(如果是,则函数使用“now”)。
*@param{Number}levels:您希望公布的详细信息数量(1=“2个月内”,2=“2个月内,20天内”,…)
*@param{Boolean}前缀:在返回字符串中添加“in”或“ago”
*@return{String}两个日期之间的差异。
*/
函数getNiceTime(fromDate、toDate、levels、prefix){
变量lang={
“日期过去”:“{0}年前”,
“date.future”:“在{0}”中,
“date.now”:“now”,
“日期.年份”:“{0}年”,
“日期年”:“{0}年”,
“date.years.prefixed:“{0}年”,
“日期.月份”:“{0}个月”,
“日期.月份”:“{0}个月”,
“date.months.prefixed:“{0}个月”,
“date.day”:“{0}天”,
“date.days”:“{0}天”,
“date.days.prefixed”:“{0}天”,
“date.hour”:“{0}小时”,
“date.hours”:“{0}小时”,
“date.hours.prefixed”:“{0}小时”,
“date.minute”:“{0}分钟”,
“date.minutes”:“{0}分钟”,
“date.minutes.prefixed”:“{0}分钟”,
“date.second”:“{0}秒”,
“date.seconds”:“{0}秒”,
“date.seconds.prefixed”:“{0}秒”,
},
langFn=函数(id,参数){
var returnValue=lang[id]| |“”;
如果(参数){
对于(变量i=0;i 0){
var langSingle=“date.year”+(前缀?:”),
langMultiple=“date.years”+(前缀?.prefixed):”;
returnString+=(计数>0?,':'')+(年份>1?langFn(langMultiple,[years]):langFn(langSingle,[years]);
计数++;
}
var months=date.getMonth();
如果(计数<级别和月份>0){
var langSingle=“date.month”+(前缀?:”),
langMultiple=“date.months”+(前缀?.prefixed):”;
returnString+=(计数>0?,':'')+(月份>1?langFn(langMultiple,[months]):langFn(langSingle,[months]);
计数++;
}否则{
如果(计数>0)
计数=99;
}
var days=date.getDate()-1;
如果(计数<级别和天数>0){
var langSingle=“date.day”+(前缀?:”),
langMultiple=“date.days”+(前缀?.prefixed):”;
returnString+=(计数>0?,':'')+(天>1?langFn(langMultiple,[days]):langFn(langSingle,[days]);
计数++;
}否则{
如果(计数>0)
计数=99;
}
var hours=date.getHours();
如果(计数0){
var langSingle=“date.hour”+(前缀?”:“”),
langMultiple=“date.hours”+(前缀?.prefixed):”;
returnString+=(计数>0?,':'')+(小时数>1?langFn(langMultiple,[hours]):langFn(langSingle,[hours]);
计数++;
}否则{
如果(计数>0)
计数=99;
}
var minutes=date.getMinutes();
如果(计数<级别和分钟数>0){
var langSingle=“date.minute”+(前缀?:”),
langMultiple=“date.minutes”+(前缀?.prefixed):”;
returnString+=(计数>0?,':'')+(分钟>1?langFn(langMultiple,[minutes]):langFn(langSingle,[minutes]);
计数++;
}否则{
如果(计数>0)
计数=99;
}
var seconds=date.getSeconds();
如果(计数0){
var langSingle=“date.second”+(前缀?:”),
langMultiple=“date.seconds”+(前缀?.prefixed):”;
returnString+=(计数>0?,':'')+(秒>1?langFn(langMultiple,[秒
/**
 * Function to print date diffs.
 * 
 * @param {Date} fromDate: The valid start date
 * @param {Date} toDate: The end date. Can be null (if so the function uses "now").
 * @param {Number} levels: The number of details you want to get out (1="in 2 Months",2="in 2 Months, 20 Days",...)
 * @param {Boolean} prefix: adds "in" or "ago" to the return string
 * @return {String} Diffrence between the two dates.
 */
function getNiceTime(fromDate, toDate, levels, prefix){
    var lang = {
            "date.past": "{0} ago",
            "date.future": "in {0}",
            "date.now": "now",
            "date.year": "{0} year",
            "date.years": "{0} years",
            "date.years.prefixed": "{0} years",
            "date.month": "{0} month",
            "date.months": "{0} months",
            "date.months.prefixed": "{0} months",
            "date.day": "{0} day",
            "date.days": "{0} days",
            "date.days.prefixed": "{0} days",
            "date.hour": "{0} hour",
            "date.hours": "{0} hours",
            "date.hours.prefixed": "{0} hours",
            "date.minute": "{0} minute",
            "date.minutes": "{0} minutes",
            "date.minutes.prefixed": "{0} minutes",
            "date.second": "{0} second",
            "date.seconds": "{0} seconds",
            "date.seconds.prefixed": "{0} seconds",
        },
        langFn = function(id,params){
            var returnValue = lang[id] || "";
            if(params){
                for(var i=0;i<params.length;i++){
                    returnValue = returnValue.replace("{"+i+"}",params[i]);
                }
            }
            return returnValue;
        },
        toDate = toDate ? toDate : new Date(),
        diff = fromDate - toDate,
        past = diff < 0 ? true : false,
        diff = diff < 0 ? diff * -1 : diff,
        date = new Date(new Date(1970,0,1,0).getTime()+diff),
        returnString = '',
        count = 0,
        years = (date.getFullYear() - 1970);
    if(years > 0){
        var langSingle = "date.year" + (prefix ? "" : ""),
            langMultiple = "date.years" + (prefix ? ".prefixed" : "");
        returnString += (count > 0 ?  ', ' : '') + (years > 1 ? langFn(langMultiple,[years]) : langFn(langSingle,[years]));
        count ++;
    }
    var months = date.getMonth();
    if(count < levels && months > 0){
        var langSingle = "date.month" + (prefix ? "" : ""),
            langMultiple = "date.months" + (prefix ? ".prefixed" : "");
        returnString += (count > 0 ?  ', ' : '') + (months > 1 ? langFn(langMultiple,[months]) : langFn(langSingle,[months]));
        count ++;
    } else {
        if(count > 0)
            count = 99;
    }
    var days = date.getDate() - 1;
    if(count < levels && days > 0){
        var langSingle = "date.day" + (prefix ? "" : ""),
            langMultiple = "date.days" + (prefix ? ".prefixed" : "");
        returnString += (count > 0 ?  ', ' : '') + (days > 1 ? langFn(langMultiple,[days]) : langFn(langSingle,[days]));
        count ++;
    } else {
        if(count > 0)
            count = 99;
    }
    var hours = date.getHours();
    if(count < levels && hours > 0){
        var langSingle = "date.hour" + (prefix ? "" : ""),
            langMultiple = "date.hours" + (prefix ? ".prefixed" : "");
        returnString += (count > 0 ?  ', ' : '') + (hours > 1 ? langFn(langMultiple,[hours]) : langFn(langSingle,[hours]));
        count ++;
    } else {
        if(count > 0)
            count = 99;
    }
    var minutes = date.getMinutes();
    if(count < levels && minutes > 0){
        var langSingle = "date.minute" + (prefix ? "" : ""),
            langMultiple = "date.minutes" + (prefix ? ".prefixed" : "");
        returnString += (count > 0 ?  ', ' : '') + (minutes > 1 ? langFn(langMultiple,[minutes]) : langFn(langSingle,[minutes]));
        count ++;
    } else {
        if(count > 0)
            count = 99;
    }
    var seconds = date.getSeconds();
    if(count < levels && seconds > 0){
        var langSingle = "date.second" + (prefix ? "" : ""),
            langMultiple = "date.seconds" + (prefix ? ".prefixed" : "");
        returnString += (count > 0 ?  ', ' : '') + (seconds > 1 ? langFn(langMultiple,[seconds]) : langFn(langSingle,[seconds]));
        count ++;
    } else {
        if(count > 0)
            count = 99;
    }
    if(prefix){
        if(returnString == ""){
            returnString = langFn("date.now");
        } else if(past)
            returnString = langFn("date.past",[returnString]);
        else
            returnString = langFn("date.future",[returnString]);
    }
    return returnString;
}
Date.dateDiff = function(d1, d2) {
    d1 /= 1000;
    d2 /= 1000;
    if (d1 > d2) d2 = [d1, d1 = d2][0];

    var diffs = {
        year: 0,
        month: 0,
        day: 0,
        hour: 0,
        minute: 0,
        second: 0
    }

    $.each(diffs, function(interval) {
        while (d2 >= (d3 = Date.strtotime('+1 '+interval, d1))) {
            d1 = d3;
            ++diffs[interval];
        }
    });

    return diffs;
};
> d1 = new Date(2000, 0, 1)
Sat Jan 01 2000 00:00:00 GMT+0100 (CET)

> d2 = new Date(2013, 9, 6)
Sun Oct 06 2013 00:00:00 GMT+0200 (CEST)

> Date.dateDiff(d1, d2)
Object {
  day: 5
  hour: 0
  minute: 0
  month: 9
  second: 0
  year: 13
}
var sdt = new Date('1972-11-30');
var difdt = new Date(new Date() - sdt);
alert((difdt.toISOString().slice(0, 4) - 1970) + "Y " + (difdt.getMonth()+1) + "M " + difdt.getDate() + "D");
// Extension for Date
Date.difference = function (dateFrom, dateTo) {
  var diff = { TotalMs: dateTo - dateFrom };
  diff.Days = Math.floor(diff.TotalMs / 86400000);

  var remHrs = diff.TotalMs % 86400000;
  var remMin = remHrs % 3600000;
  var remS   = remMin % 60000;

  diff.Hours        = Math.floor(remHrs / 3600000);
  diff.Minutes      = Math.floor(remMin / 60000);
  diff.Seconds      = Math.floor(remS   / 1000);
  diff.Milliseconds = Math.floor(remS % 1000);
  return diff;
};

// Usage
var a = new Date(2014, 05, 12, 00, 5, 45, 30); //a: Thu Jun 12 2014 00:05:45 GMT+0400 
var b = new Date(2014, 02, 12, 00, 0, 25, 0);  //b: Wed Mar 12 2014 00:00:25 GMT+0400
var diff = Date.difference(b, a);
/* diff: {
  Days: 92
  Hours: 0
  Minutes: 5
  Seconds: 20
  Milliseconds: 30
  TotalMs: 7949120030
} */
var f1 = this.getField("LeaseExpiration");
var g1 = this.getField("LeaseStart");


var end = f1.value
var begin = g1.value
var e = new Date(end);
var b = new Date(begin);
var bMonth = b.getMonth();
var bYear = b.getFullYear();
var eYear = e.getFullYear();
var eMonth = e.getMonth();
var bDay = b.getDate();
var eDay = e.getDate() + 1;

if ((eMonth == 0)||(eMonth == 2)||(eMonth == 4)|| (eMonth == 6) || (eMonth == 7) ||(eMonth == 9)||(eMonth == 11))

{
var eDays =  31;
}

if ((eMonth == 3)||(eMonth == 5)||(eMonth == 8)|| (eMonth == 10))

{
var eDays = 30;
}

if (eMonth == 1&&((eYear % 4 == 0) && (eYear % 100 != 0)) || (eYear % 400 == 0))
{
var eDays = 29;
}

if (eMonth == 1&&((eYear % 4 != 0) || (eYear % 100 == 0)))
{
var eDays = 28;
}


if ((bMonth == 0)||(bMonth == 2)||(bMonth == 4)|| (bMonth == 6) || (bMonth == 7) ||(bMonth == 9)||(bMonth == 11))

{
var bDays =  31;
}

if ((bMonth == 3)||(bMonth == 5)||(bMonth == 8)|| (bMonth == 10))

{
var bDays = 30;
}

if (bMonth == 1&&((bYear % 4 == 0) && (bYear % 100 != 0)) || (bYear % 400 == 0))
{
var bDays = 29;
}

if (bMonth == 1&&((bYear % 4 != 0) || (bYear % 100 == 0)))
{
var bDays = 28;
}


var FirstMonthDiff = bDays - bDay + 1;


if (eDay - bDay < 0)
{

eMonth = eMonth - 1;
eDay = eDay + eDays;

}

var daysDiff = eDay - bDay;

if(eMonth - bMonth < 0)
{
eYear = eYear - 1;
eMonth = eMonth + 12;
}

var monthDiff = eMonth - bMonth;

var yearDiff = eYear - bYear;

if (daysDiff == eDays)
{
daysDiff = 0;
monthDiff = monthDiff + 1;

if (monthDiff == 12)
{
monthDiff = 0;
yearDiff = yearDiff + 1;
}

}

if ((FirstMonthDiff != bDays)&&(eDay - 1 == eDays))

{
daysDiff = FirstMonthDiff;

}
event.value = yearDiff + " Year(s)" + " " + monthDiff + " month(s) " + daysDiff + " days(s)"
function monthDiff(d2, d1) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth() + 1;
    months += d2.getMonth() + 1;
    return months <= 0 ? 0 : months;
}

function daysInMonth(date) {
    return new Date(date.getYear(), date.getMonth() + 1, 0).getDate();
}    

function diffDate(date1, date2) {
    if (date2 && date2.getTime() && !isNaN(date2.getTime())) {
        var months = monthDiff(date1, date2);
        var days = 0;

        if (date1.getUTCDate() >= date2.getUTCDate()) {
            days = date1.getUTCDate() - date2.getUTCDate();
        }
        else {
            months--;
            days = date1.getUTCDate() - date2.getUTCDate() + daysInMonth(date2);
        }

        // Use the variables months and days how you need them.
    }
}
var datediff = function(start, end) {
  var diff = { years: 0, months: 0, days: 0 };
  var timeDiff = end - start;

  if (timeDiff > 0) {
    diff.years = end.getFullYear() - start.getFullYear();
    diff.months = end.getMonth() - start.getMonth();
    diff.days = end.getDate() - start.getDate();

    if (diff.months < 0) {
      diff.years--;
      diff.months += 12;
    }

    if (diff.days < 0) {
      diff.months = Math.max(0, diff.months - 1);
      diff.days += 30;
    }
  }

  return diff;
};
function dateDiff(date) {
    date = date.split('-');
    var today = new Date();
    var year = today.getFullYear();
    var month = today.getMonth() + 1;
    var day = today.getDate();
    var yy = parseInt(date[0]);
    var mm = parseInt(date[1]);
    var dd = parseInt(date[2]);
    var years, months, days;
    // months
    months = month - mm;
    if (day < dd) {
        months = months - 1;
    }
    // years
    years = year - yy;
    if (month * 100 + day < mm * 100 + dd) {
        years = years - 1;
        months = months + 12;
    }
    // days
    days = Math.floor((today.getTime() - (new Date(yy + years, mm + months - 1, dd)).getTime()) / (24 * 60 * 60 * 1000));
    //
    return {years: years, months: months, days: days};
}
function dateDiff(startingDate, endingDate) {
    var startDate = new Date(new Date(startingDate).toISOString().substr(0, 10));
    if (!endingDate) {
        endingDate = new Date().toISOString().substr(0, 10);    // need date in YYYY-MM-DD format
    }
    var endDate = new Date(endingDate);
    if (startDate > endDate) {
        var swap = startDate;
        startDate = endDate;
        endDate = swap;
    }
    var startYear = startDate.getFullYear();
    var february = (startYear % 4 === 0 && startYear % 100 !== 0) || startYear % 400 === 0 ? 29 : 28;
    var daysInMonth = [31, february, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    var yearDiff = endDate.getFullYear() - startYear;
    var monthDiff = endDate.getMonth() - startDate.getMonth();
    if (monthDiff < 0) {
        yearDiff--;
        monthDiff += 12;
    }
    var dayDiff = endDate.getDate() - startDate.getDate();
    if (dayDiff < 0) {
        if (monthDiff > 0) {
            monthDiff--;
        } else {
            yearDiff--;
            monthDiff = 11;
        }
        dayDiff += daysInMonth[startDate.getMonth()];
    }

    return yearDiff + 'Y ' + monthDiff + 'M ' + dayDiff + 'D';
}
// based on a current date of 2019-05-10
dateDiff('2019-05-10'); // 0Y 0M 0D
dateDiff('2019-05-09'); // 0Y 0M 1D
dateDiff('2018-05-09'); // 1Y 0M 1D
dateDiff('2018-05-18'); // 0Y 11M 23D
dateDiff('2019-01-09'); // 0Y 4M 1D
dateDiff('2019-02-10'); // 0Y 3M 0D
dateDiff('2019-02-11'); // 0Y 2M 27D
dateDiff('2016-02-11'); // 3Y 2M 28D - leap year
dateDiff('1972-11-30'); // 46Y 5M 10D
dateDiff('2016-02-11', '2017-02-11'); // 1Y 0M 0D
dateDiff('2016-02-11', '2016-03-10'); // 0Y 0M 28D - leap year
dateDiff('2100-02-11', '2100-03-10'); // 0Y 0M 27D - not a leap year
dateDiff('2017-02-11', '2016-02-11'); // 1Y 0M 0D - swapped dates to return correct result
dateDiff(new Date() - 1000 * 60 * 60 * 24); // 0Y 0M 1D
// startDate must be a date string
function dateAgo(date) {
    var startDate = new Date(date);
    var diffDate = new Date(new Date() - startDate);
    return ((diffDate.toISOString().slice(0, 4) - 1970) + "Y " +
        diffDate.getMonth() + "M " + (diffDate.getDate()-1) + "D");
}
// based on a current date of 2018-03-09
dateAgo('1972-11-30'); // "45Y 3M 9D"
dateAgo('2017-03-09'); // "1Y 0M 0D"
dateAgo('2018-01-09'); // "0Y 2M 0D"
dateAgo('2018-02-09'); // "0Y 0M 28D" -- a little odd, but not wrong
dateAgo('2018-02-01'); // "0Y 1M 5D" -- definitely "feels" wrong
dateAgo('2018-03-09'); // "0Y 0M 0D"
dateDifference(actualDate) {
            // Calculate time between two dates:
            const date1 = actualDate; // the date you already commented/ posted
            const date2: any = new Date(); // today

            let r = {}; // object for clarity
            let message: string;

            const diffInSeconds = Math.abs(date2 - date1) / 1000;
            const days = Math.floor(diffInSeconds / 60 / 60 / 24);
            const hours = Math.floor(diffInSeconds / 60 / 60 % 24);
            const minutes = Math.floor(diffInSeconds / 60 % 60);
            const seconds = Math.floor(diffInSeconds % 60);
            const milliseconds = 
           Math.round((diffInSeconds - Math.floor(diffInSeconds)) * 1000);

            const months = Math.floor(days / 31);
            const years = Math.floor(months / 12);

            // the below object is just optional 
            // if you want to return an object instead of a message
            r = {
                years: years,
                months: months,
                days: days,
                hours: hours,
                minutes: minutes,
                seconds: seconds,
                milliseconds: milliseconds
            };

            // check if difference is in years or months
            if (years === 0 && months === 0) {
                // show in days if no years / months
                if (days > 0) {
                    if (days === 1) {
                        message = days + ' day';
                    } else { message = days + ' days'; }
                }  else if (hours > 0) {
                    if (hours === 1) {
                        message = hours + ' hour';
                    } else {
                        message = hours + ' hours';
                    }
                } else {
                    // show in minutes if no years / months / days
                    if (minutes === 1) {
                        message = minutes + ' minute';
                    } else {message = minutes + ' minutes';}  
                }
            } else if (years === 0 && months > 0) {
                // show in months if no years
                if (months === 1) {
                    message = months + ' month';
                } else {message = months + ' months';}
            } else if (years > 0) {
                // show in years if years exist
                if (years === 1) {
                    message = years + ' year';
                } else {message = years + ' years';}
            }

            return 'Posted ' + message + ' ago'; 
     // this is the message a user see in the view
        }
    var mins;
    var hours;
    var days;
    var months;
    var years;

    var diff = new Date() - new Date(yourOldDate);  
// yourOldDate may be is coming from DB, for example, but it should be in the correct format ("MM/dd/yyyy hh:mm:ss:fff tt")

    years = Math.floor((diff) / (1000 * 60 * 60 * 24 * 365));
    diff = Math.floor((diff) % (1000 * 60 * 60 * 24 * 365));
    months = Math.floor((diff) / (1000 * 60 * 60 * 24 * 30));
    diff = Math.floor((diff) % (1000 * 60 * 60 * 24 * 30));
    days = Math.floor((diff) / (1000 * 60 * 60 * 24));
    diff = Math.floor((diff) % (1000 * 60 * 60 * 24));
    hours = Math.floor((diff) / (1000 * 60 * 60));
    diff = Math.floor((diff) % (1000 * 60 * 60));
    mins = Math.floor((diff) / (1000 * 60));
   let startDate = moment(new Date('2017-05-12')); // yyyy-MM-dd
   let endDate = moment(new Date('2018-09-14')); // yyyy-MM-dd

   let Years = newDate.diff(date, 'years');
   let months = newDate.diff(date, 'months');
   let days = newDate.diff(date, 'days');

console.log("Year: " + Years, ", Month: " months-(Years*12), ", Days: " days-(Years*365.25)-((365.25*(days- (Years*12)))/12));
var sample1 = all('2/13/2018', '3/15/2018'); // {'M/D/YYYY'} 30, Y: 0 , M: 1 , D: 2
console.log(sample1);

var sample2 = all('10/09/2019', '7/7/2020'); // 272, Y: 0 , M: 8 , D: 29
console.log(sample2);

function all(start, end) {
    dateDiffInDays(start, end);
    dateDiffInDays_Months_Years(start, end);

    try {
        dateDiffUsingMoment(start, end);
    } catch (e) {
        console.log(e); 
    }
}
Date.getFormattedDateDiff = function(date1, date2) {
var b = moment(date1),
  a = moment(date2),
  intervals = ['years','months','weeks','days'],
  out = [];

for(var i=0; i<intervals.length; i++){
  var diff = a.diff(b, intervals[i]);
  b.add(diff, intervals[i]);
  out.push(diff + ' ' + intervals[i]);
 }
 return out.join(', ');
 };

 var today   = new Date(),
 newYear = new Date(today.getFullYear(), 0, 1),
 y2k     = new Date(2000, 0, 1);

 //(AS OF NOV 29, 2016)
 //Time since New Year: 0 years, 10 months, 4 weeks, 0 days
 console.log( 'Time since New Year: ' + Date.getFormattedDateDiff(newYear, today) );

 //Time since Y2K: 16 years, 10 months, 4 weeks, 0 days
 console.log( 'Time since Y2K: ' + Date.getFormattedDateDiff(y2k, today) );
<html>
  <head>
    <title> Age Calculator</title>
  </head>

  <input type="date" id="startDate" value="2000-01-01">
  <input type="date" id="endDate"  value="2020-01-01">
  <button onclick="getAge(new Date(document.getElementById('startDate').value), new Date(document.getElementById('endDate').value))">Check Age</button>
  <script>
    function getAge (startDate, endDate) {
      var diff = endDate-startDate
      var age = new Date(new Date("0000-01-01").getTime()+diff)
      var years = age.getFullYear()
      var months = age.getMonth()
      var days = age.getDate()
      console.log(years,"years",months,"months",days-1,"days")
      return (years+"years "+ months+ "months"+ days,"days")
    }
  </script>
</html>
{
  "years": 0,
  "months": 0,
  "days": 0,
  "hours": 19,
  "minutes": 35,
  "seconds": 24
}
//************************** Enter your dates here **********************//

var startDate = "10/05/2014";
var endDate = "11/3/2016"

//******* and press "Run", you will see the result in a popup *********//



var noofdays = 0;
var sdArr = startDate.split("/");
var startDateDay = parseInt(sdArr[0]);
var startDateMonth = parseInt(sdArr[1]);
var startDateYear = parseInt(sdArr[2]);
sdArr = endDate.split("/")
var endDateDay = parseInt(sdArr[0]);
var endDateMonth = parseInt(sdArr[1]);
var endDateYear = parseInt(sdArr[2]);

console.log(startDateDay+' '+startDateMonth+' '+startDateYear);
var yeardays = 365;
var monthArr = [31,,31,30,31,30,31,31,30,31,30,31];
var noofyears = 0
var noofmonths = 0;

if((startDateYear%4)==0) monthArr[1]=29;
else monthArr[1]=28;

if(startDateYear == endDateYear){

    noofyears = 0;
    noofmonths = getMonthDiff(startDate,endDate);
    if(noofmonths < 0) noofmonths = 0;
    noofdays = getDayDiff(startDate,endDate);
   
}else{
    if(endDateMonth < startDateMonth){
        noofyears = (endDateYear - startDateYear)-1;  
    if(noofyears < 1) noofyears = 0;
  }else{
            noofyears = endDateYear - startDateYear;  
  }
    noofmonths = getMonthDiff(startDate,endDate);
    if(noofmonths < 0) noofmonths = 0;
    noofdays = getDayDiff(startDate,endDate);   
}
 
 alert(noofyears+' year, '+ noofmonths+' months, '+ noofdays+' days'); 

function getDayDiff(startDate,endDate){ 
    if(endDateDay >=startDateDay){
      noofdays = 0;
      if(endDateDay > startDateDay) {
        noofdays = endDateDay - startDateDay;
       }
     }else{
            if((endDateYear%4)==0) {
            monthArr[1]=29;
        }else{
            monthArr[1] = 28;
        }
        
        if(endDateMonth != 1)
        noofdays = (monthArr[endDateMonth-2]-startDateDay) + endDateDay;
        else
        noofdays = (monthArr[11]-startDateDay) + endDateDay;
     }
    return noofdays;
}

function getMonthDiff(startDate,endDate){
        if(endDateMonth > startDateMonth){
        noofmonths = endDateMonth - startDateMonth;
        if(endDateDay < startDateDay){
                noofmonths--;
            }
      }else{
        noofmonths = (12-startDateMonth) + endDateMonth;
        if(endDateDay < startDateDay){
                noofmonths--;
            }
     }

return noofmonths;
}
export const getAgeDetails = (oldDate: dayjs.Dayjs, newDate: dayjs.Dayjs) => {
  const years = newDate.diff(oldDate, 'year');
  const months = newDate.diff(oldDate, 'month') - years * 12;
  const days = newDate.diff(oldDate.add(years, 'year').add(months, 'month'), 'day');

  return {
    years,
    months,
    days,
    allDays: newDate.diff(oldDate, 'day'),
  };
};
let startDate = Date.parse("2010-10-01 00:00:00 UTC");
let endDate = Date.parse("2020-11-01 00:00:00 UTC");

let duration = intervalToDuration({start: startDate, end: endDate});

let durationInWords = formatDuration(duration, {format: ["years", "months", "days"]}); //output: 10 years 1 month
var momenti = require('moment-hijri')

    //calculate hijri
    var strt = await momenti(somedateobject)
    var until = await momenti()
    
    var years = await 0
    var months = await 0
    var days = await 0

    while(strt.valueOf() < until.valueOf()){
        await strt.add(1, 'iYear');
        await years++
    }
    await strt.subtract(1, 'iYear');
    await years--
    
    while(strt.valueOf() < until.valueOf()){
        await strt.add(1, 'iMonth');
        await months++
    }
    await strt.subtract(1, 'iMonth');
    await months--

    while(strt.valueOf() < until.valueOf()){
        await strt.add(1, 'day');
        await days++
    }
    await strt.subtract(1, 'day');
    await days--


    await console.log(years)
    await console.log(months)
    await console.log(days)
import * as dateFns from "https://cdn.skypack.dev/date-fns@2.22.1";

function getElapsedTime(pastDate) {
  
  const duration = dateFns.intervalToDuration({
    start: new Date(pastDate),
    end: new Date(),
  });

  let [years, months, days] = ["", "", ""];

  if (duration.years > 0) {
    years = duration.years === 1 ? "1 year" : `${duration.years} years`;
  }
  if (duration.months > 0) {
    months = duration.months === 1 ? "1 month" : `${duration.months} months`;
  }
  if (duration.days > 0) {
    days = duration.days === 1 ? "1 day" : `${duration.days} days`;
  }

  let response = [years, months, days].filter(Boolean);

  switch (response.length) {
    case 3:
      response[1] += " and";
      response[0] += ",";
      break;
    case 2:
      response[0] += " and";
      break;
  }
  return response.join(" ");
}