Pankaj Parashar
Pankaj Parashar

Reputation: 10232

Calculate time elapsed using javascript

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

For example, my birth date is 15-Oct-1989, 00 hrs 00 mins 00 secs. Hence, time elapsed since my birth date is,

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

I want to achieve the same output using JavaScript code. Any link or so will certainly help in this case.

Upvotes: 5

Views: 27834

Answers (12)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324820

Since my previous answer has people missing the point entirely, here's a port of PHP code I have to do the same thing:

    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:

console.log(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 was asking for.

Upvotes: 10

Olfredos6
Olfredos6

Reputation: 886

I came up with the following:

let getTimeElpasedString = (datetime, depth=1 )=>{
    /*
        depth = 0 means start at milliseconds
        depth = 1 means start at seconds
        ...
    */
    datetime = Date.parse(datetime).getElapsed()
    console.log(datetime)
    let dividers = [1000, 60, 60, 24, 7]
    let str = ''
    let units = ["milliseconds", "seconds", "minutes", "hours", "days"]
    let reminders = []
    dividers.forEach(d=>{
        reminders.push(datetime % d)
        datetime = parseInt(datetime/d) 
    })
    reminders = reminders.slice(depth).reverse()
    units = units.slice(depth).reverse()
    for(let i=0; i<reminders.length; i++){
        // skip which is equal to zero
        if(reminders[i] != 0)
            str += `${reminders[i]} ${units[i]} `
    }
    return str + "ago"
}

Upvotes: 0

Rishab
Rishab

Reputation: 1532

Here is simple algorithm for finding the elapse 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;
  }

Upvotes: 0

agm1984
agm1984

Reputation: 17188

Here is a quick algorithm for displaying time elapsed since a 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))

(new Date()).valueOf() returns the number of seconds elapsed since Jan 1, 1970.

After you get that, you just need the timestamp of your event, and you can subtract it from the current time. This leaves the number of seconds elapsed, which can be converted into a human readable format by dividing by the correct number of units.

For example, 3000 milliseconds is 300 seconds. The algorithm I showed works with millisecond timestamps (divide everything by 1000 for seconds), so in the algorithm, 3000 would be be greater than MINUTE but less than HOUR, so it would return 3000 / MINUTE and return 3s.

This algorithm is useful if you are displaying a card, such as a job posting that was posted 2d ago.

I didn't like most of the other answers I found because they were not simple enough or readable enough. I hope my answer is quickly understandable.

Upvotes: 0

Nishchal joshi
Nishchal joshi

Reputation: 31

Here is an easy way to calculate elapsed time.

  1. Calculate difference between origin date and today in milliseconds
  2. Pass this difference to a Date object called result
  3. Remember from Date Object definition that that result object is milliseconds from 01/01/1970 00:00:00.
  4. Inspect this result object to get Years, Months, and so on.

Here is the code to do so.

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();

Here is something you can play around with: https://jsfiddle.net/nishchal/u8gt2gwq/4/

Upvotes: 2

Try something like this:

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

Read MDN for further info. That'll give you some idea how to format the result.

Upvotes: 12

gero
gero

Reputation: 1

I like this one:

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+'s '+m+'mn '+h+'h '+j+'j (or '+x+'ms).';}

Upvotes: 0

Hexxxer
Hexxxer

Reputation: 67

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. There were a number of errors in his that stopped this script from working correctly...

Upvotes: 2

Obie
Obie

Reputation: 680

Use Moment.js for parsing, validating, manipulating, and formatting dates in Javascript. Only 5.5k so not much of a good reason to do this kind of low-level code yourself these days.

http://momentjs.com/

Upvotes: 3

Kos
Kos

Reputation: 72319

First of all, what you demand is a bit imprecise. We know that a minute = 60 seconds, a hour = 60 minutes... And it stops here. A day can be either 24 or just a little more than 24 hours, depending how you treat leap years, and "one month" doesn't even try to represent a time span precisely.

Hence: Either keep your timespans as hours, or establish an approximation to deal with leap years etc. Dates and date differences (timespans) are different concepts and need to always be treated differently.

Anyway, as for the code, I'd simply 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

Upvotes: 7

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324820

If you want to calculate to the number of days, or even weeks, you can do this just by subtracting the current timestamp from your birthday's timestamp and divide the number into its component time units.

However if you want months and years, it's a bit more complicated due to the variable number of days in a month.

Perhaps the easiest way to go about it is as follows:

  1. Get the difference in years (currentYear - birthYear)
  2. Get the difference in months (currentMonth - birthMonth)
  3. Repeat for all units
  4. If any unit is negative, subtract 1 from the unit above and add however many of the current unit make up the bigger unit.

The complication arises when you want to find 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 any more help.

Upvotes: 2

David
David

Reputation: 219096

Take a look at the JavaScript Date object. Specifically, on that page, look for 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, the start would be a given date:

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

Upvotes: 2

Related Questions