简体   繁体   中英

Calculate difference between two timestamps

I'm using the twitch api and TMI.JS

I'm trying to fetch the timestamp of followed_at . The timestamp I got was 2021-12-25T15:49:57Z , how would I go about getting the current timestamp, and then calculating the difference. So in this instance it would return followername has been following streamername for 20 days 19 hours (at the time of writing it's been 20 days and 19 hours since the followed_at timestamp.)

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




}

Above is my code for fetching it, and then sending it to the channel.

Here's how you can do it:

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

And that's the way to get days and hours:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM