【问题标题】:Find Time Between Two Dates JSON [duplicate]查找两个日期之间的时间 JSON [重复]
【发布时间】:2020-05-14 00:43:58
【问题描述】:

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

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

所以如果data 是那个JSON 路径的变量,我可以说var memberSince = data.dateJoined;

有没有一种方法可以计算用户成为会员的年数?在伪代码中,区别如下:var memberTime = data.dateJoined - current datet

提前非常感谢!

【问题讨论】:

  • 你还会计算小时、分钟、秒和毫秒吗?
  • 已经有many questions on this topic了。研究,编写一些代码,然后在遇到问题时询问。
  • 实际上只要几年就可以了,如果我可以检查差异是否小于一年并说类似:“小于一年”

标签: javascript json date time string-parsing


【解决方案1】:

这是我制作的一个构造函数,它给出了天、小时、分钟和秒。我只是通过除以 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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    • 1970-01-01
    相关资源
    最近更新 更多