Search code examples
javascriptjsondatetimestring-parsing

Find Time Between Two Dates JSON


I'm using the khanacademy.org API scratchpads to get the JSON data for users. I am trying to calculate how long they have been a member of khan academy using the date joined and the current date.

This is what they date in JSON looks like: "dateJoined": "2018-04-24T00:07:58Z",

So if data is a variable that is that JSON path, I could say var memberSince = data.dateJoined;

Is there a way I can calculate the number of years the user has been a member? In psuedo code, this is what the difference would look like: var memberTime = data.dateJoined - current datet

Thanks a lot in advance!


Solution

  • Here is a constructor I made that gives days, hours, minutes, and seconds. I just did the approximate years by dividing by 365. Figuring the years out exactly would require more work, as you would have to incorporate leap year... but it's a start.

    function TimePassed(milliseconds = null, decimals = null){
      this.days = this.hours = this.minutes = this.seconds = 0;
      this.update = (milliseconds, decimals = null)=>{
        let h = milliseconds/86400000, d = Math.floor(h), m = (h-d)*24;
        h = Math.floor(m);
        let s = (m-h)*60;
        m = Math.floor(s); s = (s-m)*60;
        if(decimals !== null)s = +s.toFixed(decimals);
        this.days = d; this.hours = h; this.minutes = m; this.seconds = s;
        return this;
      }
      this.nowDiffObj = date=>{
        this.update(Date.now()-date.getTime());
        let d = this.days, h = this.hours, m = this.minutes, s = this.seconds;
        if(m < 10)m = '0'+m;
        if(s < 10)s = '0'+s;
        return {date:date.toString(), nowDiff:d+' days, '+h+':'+m+':'+s}
      }
      if(milliseconds !== null)this.update(milliseconds, decimals);
    }
    const dt = new Date('2018-04-24T00:07:58Z'), tp = new TimePassed(Date.now()-dt.getTime());
    console.log(Math.floor(tp.days/365));