Subtraction of dates and return the number of years, months and days

Asked

Viewed 6,646 times

4

Through two input='text' I set the starting date and the final date. By Javascript I want to subtract the final date by the initial one and return the number of years, months and days. I’m using the function Date(), but I can return only the number of days. By the function Date() can return this value?

Javascript

var data_inicial = document.getElementById('data_inicial').value;
var data_final = document.getElementById('data_final').value;

if(data_inicial != '' && data_final != ''){
    var date_admissao = new Date(data_inicial.substr(6,4), data_inicial.substr(3,2)-1, data_inicial.substr(0,2));
    var date_demissao = new Date(data_final.substr(6,4), data_final.substr(3,2)-1, data_final.substr(0,2));
    var dias_total = Math.ceil((date_demissao.getTime()-date_admissao.getTime())/1000/60/60/24);

    alert(dias_total);
}

HTML

<input type="text" name="data_inicial" id="data_inicial">
<input type="text" name="data_final" id="data_final">
  • 1

    Why don’t you use the total days to have years, months and days?

  • @Erloncharles is not duplicate. Note that I say that subtraction works. The questioning is the return of this subtraction.

  • 1

    @Felipeavelar the Date() does not have this functionality?

  • No, this should be done by hand, but are relatively simple calculations.

  • 1

    @Felipeavelar are simple if you ignore bisext/common years and if you ignore months with 28/30 or 31 days... otherwise they are not so simple...

  • Have you tried the atomic subtraction? Taking year, months and days. Even if the treatment is a little complicated, it should be easier to do than taking the total of days.

  • @Felipeavelar I tried, but it didn’t work.

Show 2 more comments

2 answers

1

Below are the methods for you to recover the difference of years, months and days.

//Diferença de anos
function diferencaAnos(date1, date2) {
  var dateParts1 = date1.split('-')
    , dateParts2 = date2.split('-')
    , d1 = new Date(dateParts1[0], dateParts1[1]-1, dateParts1[2])
    , d2 = new Date(dateParts2[0], dateParts2[1]-1, dateParts2[2])

  return new Date(d2 - d1).getYear() - new Date(0).getYear() + 1;
}

//Diferença de meses
function diferencaMeses(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth() + 1;
    months += d2.getMonth();
    return months <= 0 ? 0 : months;
}

//Diferença dias
function diferencaDias(date1, date2) {

    var ONE_DAY = 1000 * 60 * 60 * 24

    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    var difference_ms = Math.abs(date1_ms - date2_ms)

    return Math.round(difference_ms/ONE_DAY)

}

//Diferença anos, meses e dias
function diferencaAnoMesDia(date1, date2) {
    return "Anos: " + diferencaAnos(date1,date2)+" Meses: " + diferencaMeses(date1,date2)" + Dias: " + diferencaDias(date1,date2);
}
  • No Leandro, these functions are for calculations separately. In reality, what I need is to subtract two dates and inform from this subtraction the number of years, months and days.

  • I will update the answer by adding another method to do this

1

In this function you can pass by parameter which return you want, you can also customize to make more generic for your case:

function getDateDiff(date1, date2, interval) {
    var second = 1000,
    minute = second * 60,
    hour = minute * 60,
    day = hour * 24,
    week = day * 7;
    dateone = new Date(date1).getTime();
    datetwo = (date2) ? new Date().getTime() : new Date(date2).getTime();
    var timediff = datetwo - dateone;
 secdate = new Date(date2);
 firdate = new Date(date1);
    if (isNaN(timediff)) return NaN;
    switch (interval) {
    case "anos":
        return secdate.getFullYear() - firdate.getFullYear();
    case "meses":
        return ((secdate.getFullYear() * 12 + secdate.getMonth()) - (firdate.getFullYear() * 12 + firdate.getMonth()));
    case "semanas":
        return Math.floor(timediff / week);
    case "dias":
        return Math.floor(timediff / day);
    case "horas":
        return Math.floor(timediff / hour);
    case "minutos":
        return Math.floor(timediff / minute);
    case "segundos":
        return Math.floor(timediff / second);
    default:
        return undefined;
    }
}

Utilizing:

 dias = getDateDiff('2012-12-25', new Date(), 'dias');
 meses = getDateDiff('2012-12-25', new Date(), 'meses');
 anos = getDateDiff('2012-12-25', new Date(), 'anos');

Also follows the Jsfiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.