I am developing a new app and need to calculate the time elapsed between the start and end of a run.
When the run starts, I record a timestamp using the new Date() function in Firebase. (I opted for this over firestore fieldValue to avoid conflicts with other users creating timestamps simultaneously).
Before finalizing the run, I want to see the duration between the start and end times.
I retrieve the start value from Firebase and generate a temporary end value using the new Date() function.
Upon comparing these two values, it appears that Firestore alters the value once it is written to the database.
However, when I also store the endStamp in Firebase and use this value for the calculation, everything works smoothly.
Presented below is my current code:
calculateTimeBetweenStamps(run) {
const startTime = run.startTimestamp;
const endTime = new Date();
return calculateTimeBetweenStamps({
startTime: startTime,
endTime: endTime
});
}
Here's the JavaScript file containing the function:
export function calculateTimeBetweenStamps(e) {
const startTime = e.startTime;
const endTime = e.endTime;
var difference = endTime - startTime;
var sec_num = parseInt(difference, 10);
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - hours * 3600) / 60);
var seconds = sec_num - hours * 3600 - minutes * 60;
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
return `${hours}:${minutes}:${seconds}`;
}