查找两个日期之间的时间JSON

问题描述 投票:1回答:1

我正在使用khanacademy.org API暂存器来获取用户的JSON数据。我正在尝试使用加入的日期和当前日期来计算他们成为可汗学院成员的时间。

这是它们在JSON中的日期看起来像:"dateJoined": "2018-04-24T00:07:58Z",

因此,如果data是该JSON路径的变量,我可以说var memberSince = data.dateJoined;

有没有一种方法可以计算用户成为会员的年数?在伪代码中,这是类似的样子:var memberTime = data.dateJoined - current datet

非常感谢!

javascript json date time string-parsing
1个回答
0
投票

这里是我制作的构造函数,它给出了天,小时,分钟和秒。我只是用365来除以近似年份。确切地算出年份将需要更多的工作,因为您将不得不合并leap年...但这是一个开始。

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));
© www.soinside.com 2019 - 2024. All rights reserved.