Difference between two dates in years, months, days in JavaScript

前端 未结 26 2464
执念已碎
执念已碎 2020-11-22 07:18

I\'ve been searching for 4 hours now, and have not found a solution to get the difference between two dates in years, months, and days in JavaScript, like: 10th of April 201

相关标签:
26条回答
  • 2020-11-22 07:49

    I know it is an old thread, but I'd like to put my 2 cents based on the answer by @Pawel Miech.

    It is true that you need to convert the difference into milliseconds, then you need to make some math. But notice that, you need to do the math in backward manner, i.e. you need to calculate years, months, days, hours then minutes.

    I used to do some thing like this:

        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));
    

    But, of course, this is not precise because it assumes that all years have 365 days and all months have 30 days, which is not true in all cases.

    0 讨论(0)
  • 2020-11-22 07:49

    This code should give you desired results

    //************************** 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;
    }
    

    https://jsfiddle.net/moremanishk/hk8c419f/

    0 讨论(0)
  • 2020-11-22 07:50

    To calculate the difference between two dates in Years, Months, Days, Minutes, Seconds, Milliseconds using TypeScript/ JavaScript

    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
            }
    

    However, you can update the above logic for the message to show seconds and milliseconds too or else use the object 'r' to format the message whatever way you want.

    If you want to directly copy the code, you can view my gist with the above code here

    0 讨论(0)
  • 2020-11-22 07:50

    I do it this way. Precise? Maybe or maybe not. Try it

    <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>
    
    0 讨论(0)
  • 2020-11-22 07:51

    For quick and easy use I wrote this function some time ago. It returns the diff between two dates in a nice format. Feel free to use it (tested on webkit).

    /**
     * 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;
    }
    
    0 讨论(0)
  • 2020-11-22 07:51

    Neither of the codes work for me, so I use this instead for months and days:

    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.
        }
    }
    
    0 讨论(0)
提交回复
热议问题