Calculate time elapsed using javascript

I want to calculate the elapsed time since my birthday in the form (years, months, days, hours, minutes, seconds) using JavaScript.

For example, my date of birth is October 15, 1989, 00 hours 00 minutes. 00 sec. Therefore, the time elapsed since my birth

22 years 5 months 10 days 19 hours 25 minutes 25 seconds 

      

I want to get the same result using JavaScript code. Any link or so will definitely help in this case.

+4


source to share


11 replies


Try something like this:

var now = new Date();
var bDay = new Date(1989, 10, 15);
var elapsedT = now - bDay; // in ms

      



Read MDN for more information . This will give you an idea of ​​how to format the result.

+11


source


Since there are people in my previous answer missing the whole dot, here's a port of PHP code I have to do the same:

function getDaysInMonth(month,year) {     
    if( typeof year == "undefined") year = 1999; // any non-leap-year works as default     
    var currmon = new Date(year,month),     
        nextmon = new Date(year,month+1);
    return Math.floor((nextmon.getTime()-currmon.getTime())/(24*3600*1000));
} 
function getDateTimeSince(target) { // target should be a Date object
    var now = new Date(), diff, yd, md, dd, hd, nd, sd, out = [];
    diff = Math.floor(now.getTime()-target.getTime()/1000);
    yd = target.getFullYear()-now.getFullYear();
    md = target.getMonth()-now.getMonth();
    dd = target.getDate()-now.getDate();
    hd = target.getHours()-now.getHours();
    nd = target.getMinutes()-now.getMinutes();
    sd = target.getSeconds()-now.getSeconds();
    if( md < 0) {yd--; md += 12;}
    if( dd < 0) {
        md--;
        dd += getDaysInMonth(now.getMonth()-1,now.getFullYear());
    }
    if( hd < 0) {dd--; hd += 24;}
    if( md < 0) {hd--; md += 60;}
    if( sd < 0) {md--; sd += 60;}

    if( yd > 0) out.push( yd+" year"+(yd == 1 ? "" : "s"));
    if( md > 0) out.push( md+" month"+(md == 1 ? "" : "s"));
    if( dd > 0) out.push( dd+" day"+(dd == 1 ? "" : "s"));
    if( hd > 0) out.push( hd+" hour"+(hd == 1 ? "" : "s"));
    if( nd > 0) out.push( nd+" minute"+(nd == 1 ? "" : "s"));
    if( sd > 0) out.push( sd+" second"+(sd == 1 ? "" : "s"));
    return out.join(" ");
}

      

Example:



getDateTimeSince(new Date(1992,1,6,22,30,00)); 
// my date of birth - near enough half past ten in the evening on Feb 6th 1992
> 20 years 1 month 18 days 17 hours 23 minutes 7 seconds

      

I believe this is exactly what the OP asked for.

+8


source


First of all, what you are asking is a little inaccurate. We know that minute = 60 seconds, hour = 60 minutes ... And here it stops. The day can be as long as 24 or just over 24 hours, depending on how you treat leap years, and “one month” doesn't even try to pinpoint the time interval.

Hence: either store your time intervals as hours, or set the approximation to leap years, etc. Dates and dates (time intervals) are different concepts and must always be handled differently.

Anyway, as far as the code goes, I would just go for:

var ms = new Date() - yourBirthDate;
var secs = ms/1000;

var minutes = secs    / 60 ;  secs    = secs    % 60;
var hours   = minutes / 60 ;  minutes = minutes % 60;
// and so on if you want

      

+7


source


Use Moment.js to parse, validate, manipulate and format dates in Javascript. Only 5.5k, so there isn't much of a reason to do this low-level code these days.

http://momentjs.com/

+3


source


Take a look at the JavaScript Date object . Specifically, on this page find the "Calculate Elapsed Time" section (near the bottom):

// using static methods
var start = Date.now();
// the event you'd like to time goes here:
doSomethingForALongTime();
var end = Date.now();
var elapsed = end - start; // time in milliseconds

      

In your case start

would be the given date:

var start = new Date(1989,10,15);

      

+2


source


If you want to calculate the number of days or even weeks, you can do so by simply subtracting the current timestamp from the birthday stamp and dividing it by time units.

However, if you need months and years, it is a little more difficult due to the variable number of days per month.

Perhaps the easiest way to do it:

  • Get the difference in years (current year is birth)
  • Get the difference in months (currentMonth - birthMonth)
  • Repeat for all units.
  • If any block is negative, subtract 1 from the above block and add, however, many of the current block is a large one.

A complication arises when you want to know how many days are in a given month. This can help:

function getDaysInMonth(month,year) {
    if( typeof year == "undefined") year = 1999; // any non-leap-year works as default
    var currmon = new Date(year,month),
        nextmon = new Date(year,month+1); // no need to check for December overflow - JS does this automatically
    return Math.floor((nextmon.getTime()-currmon.getTime())/24*3600);
}

      

This should be enough to get you on the right track. Let me know if you need more help.

+2


source


function getDaysInMonth(month,year) {     
    if( typeof year == "undefined") year = 1999; // any non-leap-year works as default     
    var currmon = new Date(year,month),     
        nextmon = new Date(year,month+1);
    return Math.floor((nextmon.getTime()-currmon.getTime())/(24*3600*1000));
} 
function getDateTimeSince(target) { // target should be a Date object
    var now = new Date(), yd, md, dd, hd, nd, sd, out = []; 

    yd = now.getFullYear()-target.getFullYear();
    md = now.getMonth()-target.getMonth();
    dd = now.getDate()-target.getDate();
    hd = now.getHours()-target.getHours();
    nd = now.getMinutes()-target.getMinutes();
    sd = now.getSeconds()-target.getSeconds(); 

    if( md < 0) {yd--; md += 12;}
    if( dd < 0) {
        md--;
        dd += getDaysInMonth(now.getMonth()-1,now.getFullYear());
    }
    if( hd < 0) {dd--; hd += 24;}
    if( nd < 0) {hd--; nd += 60;}
    if( sd < 0) {nd--; sd += 60;}

    if( yd > 0) out.push( yd+" year"+(yd == 1 ? "" : "s"));
    if( md > 0) out.push( md+" month"+(md == 1 ? "" : "s"));
    if( dd > 0) out.push( dd+" day"+(dd == 1 ? "" : "s"));
    if( hd > 0) out.push( hd+" hour"+(hd == 1 ? "" : "s"));
    if( nd > 0) out.push( nd+" minute"+(nd == 1 ? "" : "s"));
    if( sd > 0) out.push( sd+" second"+(sd == 1 ? "" : "s"));
    return out.join(" ");
}

      

This is a different version of Kolink's code. It had several errors that stopped working correctly with this script ...

+2


source


Here's an easy way to calculate the elapsed time.

  • Calculate difference between start date and today in milliseconds
  • Pass this difference to a Date object named result
  • Remember from the definition of a Date object that this result object is milliseconds since 01/01/1970 00:00:00.
  • Inspect this result object to get Years, Months, etc.

Here is the code for that.

Date.prototype.getElapsedTime = function() {
  var diffDate = new Date(Date.now() - this);
  return "Elapsed Time: Years: " + (diffDate.getFullYear() - 1970) + ", Months: " + diffDate.getMonth() + ", Days: " + (diffDate.getDate() - 1) + ", Hours: " + diffDate.getHours() + ", Minutes: " + diffDate.getMinutes() + ", Seconds: " + diffDate.getSeconds();
};

var from = new Date("01/08/1986 04:07:00");
document.getElementById("result").innerHTML = from.getElapsedTime();

      

You can play around with here: https://jsfiddle.net/nishchal/u8gt2gwq/4/

+1


source


I like this:

function lifeSpan(t0) {var x=new Date()-t0, a=x, i=0,s=0,m=0,h=0,j=0;
  if(a>=1){i=a%1000;a=(a-i)/1000;
  if(a>=1){s=a%60;a=(a-s)/60;
  if(a>=1){m=a%60;a=(a-m)/60;
  if(a>=1){h=a%24;a=(a-h)/24;
  if(a>=1){j=a;//...
  }}}}}
  return 'Elapsed: '+i+'ms '+s+ '+m+'mn '+h+'h '+j+'j (or '+x+'ms).';}

      

0


source


Here's a quick algorithm to display the time elapsed since unix / epoch timestamp:

const showElapsedTime = (timestamp) => {
    if (typeof timestamp !== 'number') return 'NaN'        

    const SECOND = 1000
    const MINUTE = 1000 * 60
    const HOUR = 1000 * 60 * 60
    const DAY = 1000 * 60 * 60 * 24
    const MONTH = 1000 * 60 * 60 * 24 * 30
    const YEAR = 1000 * 60 * 60 * 24 * 30 * 12
    
    const elapsed = ((new Date()).valueOf() - timestamp)
    
    if (elapsed <= MINUTE) return '${Math.round(elapsed / SECOND)}s'
    if (elapsed <= HOUR) return '${Math.round(elapsed / MINUTE)}m'
    if (elapsed <= DAY) return '${Math.round(elapsed / HOUR)}h'
    if (elapsed <= MONTH) return '${Math.round(elapsed / DAY)}d'
    if (elapsed <= YEAR) return '${Math.round(elapsed / MONTH)}mo'
    return '${Math.round(elapsed / YEAR)}y'
}
      
const createdAt = 1541301301000

console.log(showElapsedTime(createdAt + 5000000))
console.log(showElapsedTime(createdAt))
console.log(showElapsedTime(createdAt - 500000000))
      

Run code


(new Date()).valueOf()

returns the number of seconds since Jan 1, 1970.

After you get this, you just need the timestamp of your event, and you can subtract it from the current time. Thus, the number of seconds elapsed expires and can be converted to human readable format by dividing by the correct number of units.

For example, 3000 milliseconds is 300 seconds. The algorithm I showed works with timestamps in milliseconds (divide everything by 1000 in seconds), so in the algorithm 3000 will be more than MINUTE

but less than HOUR

, so it will return 3000 / MINUTE

and return 3s

.

This algorithm is useful if you are displaying a card such as a job posting that has been posted 2d ago

.

I didn't like most of the other answers I found because they weren't straightforward or readable enough. I hope my answer is quickly clear.

0


source


Here's a simple algorithm for determining the expiration time:

  time_elapsed_string = function(ptime){
    var etime = (Date.now() / 1000 | 0 ) - ptime;

    if (etime < 1)
    {
      return '0 seconds';
    }

    var a = {'31536000' :  'year',
              '2592000'  :  'month',
              '86400' :  'day',
              '3600' :  'hour',
              '60'  :  'minute',
              '1'  :  'second'
            };
    var a_plural = { 'year'   : 'years',
                      'month'  : 'months',
                      'day'    : 'days',
                      'hour'   : 'hours',
                      'minute' : 'minutes',
                      'second' : 'seconds'
                    };
    var output = '';
    $.each(a,function(secs,str){
        var d = etime / secs;
        if (d >= 1){
          var r = Math.round(d);
          output = r + ' ' + (r > 1 ? a_plural[str] : str) + ' ago';
          return true;
        }
    });
    return output;
  }
      

Run code


0


source







All Articles