在两个日期之间找到时间 JSON



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

这是他们在JSON中的日期的样子:"dateJoined": "2018-04-24T00:07:58Z",

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

有没有办法计算用户成为会员的年数?在伪代码中,这就是差异的样子:var memberTime = data.dateJoined - current datet

提前非常感谢!

这是我制作的构造函数,它给出了天、小时、分钟和秒。我只是通过除以 365 来计算大约几年。确切地计算年份需要更多的工作,因为您必须合并闰年......但这只是一个开始。

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

最新更新