Home > Enterprise >  How to calculate difference between saved timestamp and current time
How to calculate difference between saved timestamp and current time

Time:01-30

Hey everyone i saved a timestamp in this format .

enter image description here

So what i wanna do now is calculating the difference between the current time and the saved timestamap in a javascript function. But i have no idea how to do.

Hope anyone can help.

CodePudding user response:

When you fetch the document, 'timestamp' field would be of type Timestamp and you can use seconds property and current timestamp to calculate the difference as shown below:

const snap = await getDoc(docRef);
const timeDiff = Date.now() - snap.data()?.time.seconds * 1000;

console.log(`Time Difference: ${timeDiff} ms`)

CodePudding user response:

This is actually very easy to achieve. Most important to know is that the function Date.now() returns you the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.

To get the duration between to timestamps is like "end - begin = duration".

Here is a code example:

// collect the first timestamp
const beginTimestamp = Date.now()

// here comes a for loop to consume some time, otherwise you will get 0 milliseconds
for (var i=0; i<10000; i  ) {
    "Some kind of string".split("").reverse().join("")
}

// collect the second timestamp
const endTimestamp = Date.now()

// subtract the first from the second timestamp tells you the milliseconds in between of both timestamps
console.log("Duration in milliseconds:", endTimestamp - beginTimestamp)
  •  Tags:  
  • Related