Difference between dates in months javascript [duplicate]

1

I want to have the difference of months between two dates. But I'm missing something. I want to type the dates in the inputs and the result appears in another input.

var DateDiff = {

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);
}}
var dataInicio= document.getElementById("dataInicio");
var dataFinal = document.getElementById("dataFinal");
document.write("<br />Numero de <b>months</b> since "+dataInicio+": "+DateDiff.inMonths(dataInicio, dataFinal));
    
asked by anonymous 16.07.2016 / 04:42

2 answers

2

See if this is ... The accepted format is with bars: yyyy / mm / dd or dd / mm / yyyy or commas yyyy, mm, dd

<input type="date" id="dt1">Data 1</br>
<input type="date" id="dt2">Data 2</br>
<input type="text" id="result">Resultado</br>
<input type="submit" value="calcular" onclick="calcular();">
<script>
function calcular(){
var dt1 = document.getElementById("dt1").value; 
var dt2 = document.getElementById("dt2").value; 

var data1 = new Date(dt1); 
var data2 = new Date(new Date(dt2));
var total = (data2.getFullYear() - data1.getFullYear())*12 + (data2.getMonth() - data1.getMonth());
document.getElementById("result").value = total;
}
</script>

Anything says agent fits.

If any of the answers are valid, you could validate, under the green icon, below the evaluation arrows.     

16.07.2016 / 07:36
0

You need to instantiate the dates in the javascript pattern.

var DateDiff = {

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

return (d2M+12*d2Y)-(d1M+12*d1Y);
}}
var dataInicio= document.getElementById("dataInicio").value;
var dataFinal = document.getElementById("dataFinal").value;
document.write("<br />Numero de <b>months</b> since "+dataInicio+": "+DateDiff.inMonths(dataInicio, dataFinal));

Your date must be in a pattern accepted by the javascript "yyyy-mm-dd" or "mm / dd / yyyy", for example, to use new Date ().

    
16.07.2016 / 06:43