Exploring the contrast of utilizing the `new Date()` function compared to Firestore's `new

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

Answer №1

Firestore utilizes the JavaScript Date object, just like your code does. However, there is a limitation to consider as outlined in the documentation:

When stored in Cloud Firestore, precise only to microseconds; any additional precision is rounded down.

This discrepancy in dates may be what you are encountering. If you require this level of detail, it is recommended to use Timestamps in Firestore instead. This option is detailed in the documentation:

represents a point in time independent of any time zone or calendar, represented as seconds and fractions of seconds at nanosecond resolution in UTC Epoch time.

To work with this in your code, you can convert it to a date using the .toDate() function. This will provide you with a JavaScript Date object without the rounding up of precision.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JavaScript to determine the time it will take to download something

Hi everyone, I'm a beginner in javascript and I am currently working on finding the download time of a file. I have calculated the size of the file and divided it by the current time, but unfortunately, I am not getting the correct result. This is th ...

Error message: "The property or method you are trying to access is not defined

I had no issues with my app until I added the JavaScript, now I'm getting constant errors in the console. One of the errors I see is: Property or method "show" is not defined on the instance but referenced during render. Make sure that this proper ...

Achieving optimal performance with scoped CSS in Vue.js

As I work on creating a new app using VueJs, I have noticed the implementation of "css scoped" as shown below: <style scoped> .example { color: red; } </style> <template> <div class="example">hi</div> </template> ...

What is the best way to access and interpret a JSON file within an Angular application?

I am facing difficulties while trying to load a JSON file from my local disk in order to populate a FabricJS canvas with the data. Currently, I am encountering issues retrieving the data from the file. Here is what I have attempted so far. app.html < ...

Ways to establish a minimum height for material cards using Material UI

I am facing an issue with a card that contains a nested table. The card expands and shrinks based on the size of the table inside it. I want to prevent the card from shrinking when the table has no data or just one entry. Instead, I need the card to mainta ...

JPlayer experiencing technical difficulties on Internet Explorer and Opera browsers

Hey there! I'm facing an issue with my website . I've uploaded some ogg and m4a files for streaming, and while it works perfectly on Firefox, Safari, and Chrome, it's not functioning properly on IE. When I try to play a song, it seems to loa ...

What could be causing the issue of the view not showing up in AngularJS?

I've been trying to use AngularJS modules to display a view, but for some reason my page isn't showing up. Can anyone help me figure out what's going on? You can check out my code at the following link: <!DOCTYPE html> <html> & ...

Ant Design is incompatible with React JS projects and cannot be effectively utilized

import React from 'react'; import styled from "styled-components"; import {Col, Row} from "antd"; const TitleBig = styled.div` font-family: "Bebas Neue Pro"; font-size: 20px; `; const TitleSmall = styled.div` ...

Is it possible to alter the state of one page by clicking a link on another page?

Is it possible to update the state of a different page when a link is clicked and the user navigates to that page? For example: Homepage <Link href="/about"> <button>Click here for the About page</button> </Link> If a ...

What is Angular's approach to handling elements that have more than one directive?

When an element in Angular has multiple directives, each specifying a different scope definition such as scope:false, scope:true, or scope:{}, how does the framework handle this complexity? ...

What could be causing json_decode to return NULL in this scenario?

I have a custom array that I've created with the following structure: [{ "assetPreviewUrl":"pic1.jpg", "assetUrl":"pic2.jpg" }, { "assetPreviewUrl":"pic3.jpg", "assetUrl":"pic4.jpg" }] My approach involves stringifying this array and ...

Can I use AJAX to load an entire PHP file?

My goal is to trigger a PHP file for sending an email when the countdown I created reaches zero. The PHP code contains the email message and does not involve any UI elements. I suspect that my approach may be incorrect, especially since I am not very fami ...

The File Filter feature of Angular's ng2-file-upload is not functioning correctly for PNG files in the Internet Explorer

I am encountering an issue with the file uploader plugin ng2-file-upload when trying to upload a PNG file using Internet Explorer 11. For some reason, the PNG files are not being added to the queue, even though all other allowed file types work perfectly f ...

Step-by-step guide: Uploading files with Ajax in Codeigniter

I am facing an issue with updating data and uploading an image when editing a row in my grid. Although the data is successfully updated, I am encountering difficulties in saving the image file to a folder. Here is what I have tried: While using AJAX, I ...

How can one deactivate a <MenuItem> component in material-ui?

Currently, I am in the process of developing a personalized combo box using React and Material-UI. This unique combo box will exhibit the chosen value within the input, present a drop-down menu with various options (MenuItems), and feature a text box at th ...

Utilizing HTML, CSS, and JavaScript to dynamically add and remove a class from

I've been struggling with a specific issue in my 9-button grid. When I click on a button and it changes color to orange, if I click on another button, both buttons remain orange. What I want is for only one button at a time to be orange - when a new b ...

What could be the reason for the malfunction of this AngularJS data binding feature?

I am trying to create an angularjs filter that outputs HTML, similar to what is discussed in the link, but I am encountering issues. In my HTML code, I have: <ul> <li ng-repeat="book in books | filter:query"> {{book.title}} ...

Challenges encountered when uploading files

Within my react form, I have multiple files that are uploaded to be sent to the backend. Below is a snippet of code for the form submit button: const handleSubmit = async (e) => { e.preventDefault(); setDisabled(true); const ...

deliver a promise with a function's value

I have created a function to convert a file to base64 for displaying the file. ConvertFileToAddress(event): string { let localAddress: any; const reader = new FileReader(); reader.readAsDataURL(event.target['files'][0]); reader ...

Exploring cross-browser compatibility with the use of CSS3 and JavaScript

Starting a new project to create a fresh website. It seems like many people are leaning towards CSS3 and AJAX, neglecting browsers without JavaScript support. They resort to workarounds like enabling CSS3 through JavaScript in older browsers. Is this the ...