计算两个时间戳之间的差异

Calculate difference between two timestamps

我正在使用 twitch api 和 TMI.JS

我正在尝试获取 followed_at 的时间戳。我得到的时间戳是2021-12-25T15:49:57Z,我该如何获取当前时间戳,然后计算差值。因此,在这种情况下,它将 return followername has been following streamername for 20 days 19 hours (在撰写本文时,自 followed_at 时间戳以来已有 20 天 19 小时。)

if (message.toLowerCase() === '!followage')  {
client.say(channel, `@${tags.username}, does not work yet `)
  console.log(`${channel.id}`)
  console.log(`${tags['user-id']}`)
  async function getData() {
    const res = await fetch(`https://api.twitch.tv/helix/users/follows?to_id=226395001&from_id=${tags['user-id']}`, { method: 'get', headers: {
    'Client-Id': 'cut out for a reason',
    'Authorization': 'Bearer cut out for a reason'
    
  }});
  const data = await res.json();
  console.log(data)
  if (data.data[0]) {
    client.say(channel, `@${tags.username}, followed at ${data.data[0].followed_at}`)
    
  } else {
    client.say(channel, `You aren't followed!`)
  }
  }
  getData()
  




}

以上是我获取它然后发送到频道的代码。

你可以这样做:

const followedAt = new Date('2021-12-25T15:49:57Z');
const currentDate = new Date();
const diffTime = Math.abs(currentDate - followedAt);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 
console.log(diffTime + " milliseconds");
console.log(diffDays + " days");

这就是获取日期和时间的方法:

const followedAt = new Date('2021-12-25T15:49:57Z');
const currentDate = new Date();
const diffTime = Math.abs(currentDate - followedAt);
const diffTotalHours = Math.floor(diffTime / (1000 * 60 * 60)); 
const diffDays = Math.floor(diffTotalHours / 24);
const diffHoursWithoutDays = diffTotalHours % 24;

console.log(`${diffDays} days and ${diffHoursWithoutDays} hours`);