如何使用node.js在mongodb中获取createdAt之后的时间?

0dxa2lsx  于 2023-01-12  发布在  Go
关注(0)|答案(2)|浏览(84)

我想知道自创建帐户以来有多长时间了:

console.log('TIMEYWIMEY',req.user.createdAt, new Date(), new Date() - req.user.createdAt)

这将输出TIMEYWIMEY 2019-05-10T16:12:40.457Z 2019-07-26T16:05:58.142Z NaN
我不明白为什么是NaN,它们看起来都是日期,我想你可以把它们减去。

vu8f3i0k

vu8f3i0k1#

从我对这个问题的理解来看,你不应该得到有效日期的毫秒差,然后计算吗?

const d1 = createdAt.getTime();
const d2 = new Date().getTime();
const diff = d2 - d1;

然后将差值转换为所需单位。例如:

const days = diff/1000*60*60*24;
luaexgnf

luaexgnf2#

下面的函数接受一个字符串时间戳,并返回自传递时间戳以来的时间的字符串表示

function timeSince(timestamp) {
  let time = Date.parse(timestamp);
  let now = Date.now();
  let secondsPast = (now - time) / 1000;
  let suffix = 'ago';

  let intervals = {
      year: 31536000,
      month: 2592000,
      week: 604800,
      day: 86400,
      hour: 3600,
      minute: 60,
      second: 1
  };

  for (let i in intervals) {
        let interval = intervals[i];
        if (secondsPast >= interval) {
            let count = Math.floor(secondsPast / interval);
            return `${count} ${i} ${count > 1 ? 's' : ''} ${suffix}`;
        }
    }
}

您可以按如下方式使用此函数:

let timestamp = '2023-01-11T09:02:24.566Z';
console.log(timeSince(timestamp));

这将返回如下内容:

0 seconds ago

相关问题