0

I am trying through a date that in js returns me the years and months that have passed, but I only get it to show me the days

$("#nacimiento").change(function(){
  
             
 var nacimiento=$("#nacimiento").val();
 var fechaInicio = new Date(nacimiento).getTime();
 var fechaFin    = new Date('<? echo date("Y-m-d");?>').getTime();

 var diff = fechaFin - fechaInicio;
 
var tiempo=diff/(1000*60*60*24);
         
         
  
 console.log(diff/(1000*60*60*24));

 document.getElementById('meses').innerHTML=tiempo;
         
 });
imvain2
  • 15,480
  • 1
  • 16
  • 21
Kezman10
  • 3
  • 3

1 Answers1

1

You could use the Luxon package for this and create two DateTime objects and get the difference between them in Months from the Interval object and work from there.

eg

const fromUser = DateTime.fromString(nacimiento)
const fromPhp = DateTime.fromString('<? echo date("Y-m-d");?>')
const diff = Interval.fromDateTimes(fromUser, fromPhp);

const diffMonths = diff.length('months')

console.log(diffMonths)

another approach without an external package might be just using getMonth() and getFullYear() example:

const fromUser = new Date(nacimiento)
cnost fromPhp = new Date('<? echo date("Y-m-d");?>')
const months = fromUser.getMonth() -
    fromPhp.getMonth() +
    12 * (fromUser.getFullYear() - fromPhp.getFullYear())
Chris Schuld
  • 279
  • 1
  • 3
  • 11