How to find out the elapsed time?

4

Hi I wanted to take out the years, months, weeks, days and hours, seconds that have passed since a date. I have achieved what is shown below, but I can not get the exact account, nor can I subtract the time from years, months, weeks, days, etc ... so I always get what happened. I mean the years that have passed, the months that have passed, etc ... and I want the years to come out and the rest of months, days, hours and seconds. (Example: 30 years, 2 months, 1 week, 3 days, 6 hours, 28 minutes, 15 seconds)

var nacimiento = new Date(1936, 11, 29)
var hoy = new Date

var tiempoPasado= new Date() - nacimiento

//calculo segundos 
var segundos = tiempoPasado/ 1000

var minutos = segundos / 60
tiempoPasado= tiempoPasado- (minutos - segundos)

var horas = minutos / 60
tiempoPasado= tiempoPasado- ( horas - minutos)

var dias = horas / 24
tiempoPasado= tiempoPasado- (dias - horas)


var meses = dias / 30.416666666666668
tiempoPasado= tiempoPasado- (meses - dias)

var anos = meses / 12

console.log('Han pasado ${anos} años, ${meses} meses,  ${dias} dias, ${horas} horas, y ${minutos} minutos desde que naciste. Ya chocheas...!!')
    
asked by Mari Cruz 20.03.2018 в 19:01
source

2 answers

3

To perform the calculation correctly, you must start by calculating the total number of years elapsed, then subtract the years from the elapsed time, and so on until you reach the seconds.

Example:

Whereas new Date(1936, 11, 29) , is equal to 29/12/1936 ...

var nacimiento = new Date(1936, 11, 29)
var hoy = new Date()

var tiempoPasado= hoy - nacimiento
var segs = 1000;
var mins = segs * 60;
var hours = mins * 60;
var days = hours * 24;
var months = days * 30.416666666666668;
var years = months * 12;

//calculo 
var anos = Math.floor(tiempoPasado / years);

tiempoPasado = tiempoPasado - (anos * years);
var meses = Math.floor(tiempoPasado / months)

tiempoPasado = tiempoPasado - (meses * months);
var dias = Math.floor(tiempoPasado / days)

tiempoPasado = tiempoPasado - (dias * days);
var horas = Math.floor(tiempoPasado / hours)

tiempoPasado = tiempoPasado - (horas * hours);
var minutos = Math.floor(tiempoPasado / mins)

tiempoPasado = tiempoPasado - (minutos * mins);
var segundos = Math.floor(tiempoPasado / segs)

console.log('Han pasado ${anos} años, ${meses} meses,  ${dias} dias, ${horas} horas, y ${minutos} minutos desde que naciste. Ya chocheas...!!')
    
answered by 20.03.2018 / 19:33
source
1

So then you need the seconds to be updated "in real time and each time 60 seconds pass they add up one minute and every minute an hour and so on progressively?

For this you can use setTimeout so that the function is executed every second as a clock

And what else is the intention to decrease the variable timepoPasado?

I have not tested your code well but it seems to me that some accounts are wrong.

    
answered by 20.03.2018 в 19:29