8

I have two date pickers that calculates the number of days there are between the two dates. At the moment I'm outputting the number of days (see code below) which is kind of meaningless. I want to output that number in years, months, days. How can I do that?

E.g So 01/01/14 to 01/02/15 = 397 days which then becomes 1 year(s), 1 month(s), 1 day(s)

var diff = endDate - startDate;
dayCount = diff / ( 60 * 60 * 24 * 1000 ); // secs * mins * hours * milliseconds
dayCount = Math.round( dayCount ) + this.options.countAdjust;
return dayCount;
Rob
  • 6,304
  • 24
  • 83
  • 189

6 Answers6

12

You have a bug in your calculation : it's 0 month. And if you mean d/m/y then 1 year, 1 month, and 0 day old.

you said between the two dates ( not include) - look here

Anyway here is the right code which include actually count each month - how many days it has ! ( leap year consideration):

notice :

I instantiated it as d/m/yyy. feel free to send right pattern in :

alert(getAge( new Date(1978,11,22),new Date()))

function getAge(date_1, date_2)
{
  
//convert to UTC
var date2_UTC = new Date(Date.UTC(date_2.getUTCFullYear(), date_2.getUTCMonth(), date_2.getUTCDate()));
var date1_UTC = new Date(Date.UTC(date_1.getUTCFullYear(), date_1.getUTCMonth(), date_1.getUTCDate()));


var yAppendix, mAppendix, dAppendix;


//--------------------------------------------------------------
var days = date2_UTC.getDate() - date1_UTC.getDate();
if (days < 0)
{

    date2_UTC.setMonth(date2_UTC.getMonth() - 1);
    days += DaysInMonth(date2_UTC);
}
//--------------------------------------------------------------
var months = date2_UTC.getMonth() - date1_UTC.getMonth();
if (months < 0)
{
    date2_UTC.setFullYear(date2_UTC.getFullYear() - 1);
    months += 12;
}
//--------------------------------------------------------------
var years = date2_UTC.getFullYear() - date1_UTC.getFullYear();




if (years > 1) yAppendix = " years";
else yAppendix = " year";
if (months > 1) mAppendix = " months";
else mAppendix = " month";
if (days > 1) dAppendix = " days";
else dAppendix = " day";


return years + yAppendix + ", " + months + mAppendix + ", and " + days + dAppendix + " old.";
}


function DaysInMonth(date2_UTC)
{
var monthStart = new Date(date2_UTC.getFullYear(), date2_UTC.getMonth(), 1);
var monthEnd = new Date(date2_UTC.getFullYear(), date2_UTC.getMonth() + 1, 1);
var monthLength = (monthEnd - monthStart) / (1000 * 60 * 60 * 24);
return monthLength;
}


alert(getAge(new Date(1978, 11, 22), new Date()))
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • 2
    Note that the "convert to UTC" expression is misleading. ECMAScript Dates **are** UTC, no conversion required. The expression is equivalent to `date2.setUTCHours(0,0,0,0)`. The *DaysInMonth* function is unnecessarily complex ([*Get number days in a specified month*](http://stackoverflow.com/questions/315760/what-is-the-best-way-to-determine-the-number-of-days-in-a-month-with-javascript)). – RobG Feb 03 '16 at 23:47
  • this logic will not yield the accurate output because of miscalculated `getUTCMonth()` and `getMonth()` it must be added by `+1` to make it right since it is counted as index from `0(jan) to 11(dec)`. – Shift 'n Tab Apr 10 '17 at 12:09
  • @robg what exactly does setutchours 0 0 0 0 0 do ? Didnt find that in the docs (0 values) – Royi Namir May 26 '18 at 07:23
  • *setUTCHours* sets the UTC time to 00:00:00.000, see [*§ 20.3.4.30 Date.prototype.setUTCHours ( hour \[ , min \[ , sec \[ , ms \] \] \] )*](http://ecma-international.org/ecma-262/8.0/). – RobG May 26 '18 at 23:25
  • @Robg that's not what i meant. Why do you say that convert to utc is not required? And how's does setutchoyrs reolves that? – Royi Namir May 27 '18 at 06:22
  • Dates **are** UTC, they don't have a timezone. The code `var date2_UTC = new Date(Date.UTC(date_2.getUTCFullYear(), date_2.getUTCMonth(), date_2.getUTCDate()));` is identical to `var date2_UTC = new Date(date_2); date2_UTC.setUTCHours(0,0,0,0)`. Both create a "copy" of the original date with the UTC time set to 00:00:00.000, but one is a lot less code. – RobG May 27 '18 at 10:39
  • ```getUTCFullYear()``` resulted in 'getutcfullyear is not a function'. Changed it to ```getfullyear()``` – liwevire Jun 08 '21 at 14:23
1

You can use link shown below , it has more detailed explanation. JSFIDDLE The detailed code is -

var DateDiff = {

    inDays: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000));
    },

    inWeeks: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000*7));
    },

    inMonths: function(d1, d2) {
        var d1Y = d1.getFullYear();
        var d2Y = d2.getFullYear();
        var d1M = d1.getMonth();
        var d2M = d2.getMonth();

        return (d2M+12*d2Y)-(d1M+12*d1Y);
    },

    inYears: function(d1, d2) {
        return d2.getFullYear()-d1.getFullYear();
    }
}


var d1 = new Date("01/01/14");
var d2 = new Date("01/02/15");
var months= DateDiff.inYears(d1, d2)*12 ;
var month = DateDiff.inMonths(d1, d2) - months;
var days = DateDiff.inYears(d1, d2)*365;
var dy = DateDiff.inDays(d1, d2) - days;
alert(DateDiff.inYears(d1, d2) + " Year " + month + " Month "+ dy + " Days");

Link

Arindam Nayak
  • 7,346
  • 4
  • 32
  • 48
  • So if it makes a duplicate post, flag the question as a duplicate, it is useless to post an answer like that – Nicolas R Oct 02 '14 at 11:15
  • @NicolasR , done with flagging, I have never realized that, Thanks! – Arindam Nayak Oct 02 '14 at 11:22
  • that's not what he wants .look at the comments to sean – Royi Namir Oct 02 '14 at 11:48
  • @RoyiNamir , i have used OP's input values, so for particular that input, result is 1,1,1 , also OP told that too! , or am i missing anything? – Arindam Nayak Oct 02 '14 at 12:02
  • OP has mistake! dont need to be a genius to see that he's wrong – Royi Namir Oct 02 '14 at 12:02
  • @RoyiNamir , then i am still not sure, what need to be done to help OP, because, so far i have created a function to get day, month, year, and that is what needed. – Arindam Nayak Oct 02 '14 at 12:05
  • look : pure caltulation of days : ((new Date(2015,1,1))-(new Date(2014,0,1))) /(1000*60*60*24) ----> 396 days and not 397 like he said. now how do you convert this to years ? a year doesnt contain exactly 365 days ! . so look at my code to see how you subtract each section and get to the right result ( by high resiolution of how many days in each month ! - including leap years).... **look at my code** – Royi Namir Oct 02 '14 at 12:08
  • run this also http://www.timeanddate.com/date/durationresult.html?d1=1&m1=1&y1=2014&d2=1&m2=2&y2=2015 – Royi Namir Oct 02 '14 at 12:10
1
function parseDays (value) {
    const YEAR = 365, MONTH = 30, WEEK = 7;
    let year, months, week, days;
         
    year = value >= YEAR ? Math.floor(value / YEAR) : 0;
    value = year ? value - (year * YEAR) : value;
        
    months = value >= MONTH ? Math.floor((value % YEAR) / MONTH) : 0;
    value = months ? value - (months * MONTH) : value;
        
    week = value >= WEEK ? Math.floor((value % YEAR) / WEEK) : 0;
    value = week ? value - (week * WEEK) : value;
        
    days = value < WEEK ? Math.floor((value % YEAR) % WEEK) : 0;
        
    console.log(`years=${year},months=${months},weeks=${week},days=${days}`);     
}
Matul Jain
  • 78
  • 9
0

This has been answered several times befoore: See https://stackoverflow.com/a/17733753/550198

You can modify the following method quite easily to suit your purposes:

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
Community
  • 1
  • 1
Seany84
  • 5,526
  • 5
  • 42
  • 67
0

When you want to get the year and month between two date:

     var dateFrom = '2017-08-10'; 
     var dateTo ='2019-04-23';
     var date1 = new Date(dateFrom);
     var date2 = new Date(dateTo);
     var diff=0;
     var month=31;
     var days=1000*60*60*24;
     diff=date2-date1; 
     var day=(Math.floor(diff/days));   
     var years = (Math.floor(day/365));
     var months = Math.round(day % 365)/month;
    document.write(years+"year-"+months);
EzLo
  • 13,780
  • 10
  • 33
  • 38
-1

This will give you the difference between two dates, in milliseconds

var diff = Math.abs(date1 - date2);

In your example, it'd be

var diff = Math.abs(new Date() - compareDate);

You need to make sure that compareDate is a valid Date object.

Something like this will probably work for you

var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));

i.e. turning "2011-02-07 15:13:06" into new Date('2011/02/07 15:13:06'), which is a format the Date constructor can comprehend.

Answer Reference

Community
  • 1
  • 1
Fahad Hussain
  • 1,165
  • 1
  • 10
  • 17