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

What is the best way to select an HTML tag element using the :v-deep() selector?

When I utilize the following: ::v-deep img { ... } it functions but triggers a deprecation warning: [@vue/compiler-sfc] ::v-deep usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead. How can I achieve the same effect using ...

Troubleshooting issues with AngularJS routing

Having trouble clicking on the show button and seeing anything displayed. I've spent a lot of time on this without success, can someone please assist. Files.... app.js controller.js index.html show.html index.html <html ng-app='Java4sApp& ...

Can a variable be declared within the path references of the Firebase database?

In an effort to update my app's database references, I am working on implementing specific Firebase rules that involve adding buildings and depts nodes inside the user node. This decision was prompted by a discussion on best practices for writing Fire ...

Navigating arrays containing arrays/objects and updating properties in Angular using loops

My challenge involves an array containing arrays and objects. Within a function, I am attempting to assign a value to a specific property (for example, setting 'call' of $scope.companies[0].users to the value selected in a checkbox). Despite my r ...

I am unsure about how to properly implement the reduce function

I am struggling with implementing the reduce function in my code. I have data output from a map function that consists of two documents. For example, one document contains: key "_id":"AD" "values" { "numtweets" : 1, "hastags" : ...

Lack of code completion in Nuxt options API when using typescript

After setting up Nuxtjs with typescript, I noticed that there are no code completions in the template and script as expected based on the title. Here is the code: <script lang="ts"> import Vue from 'vue'; import { FeaturedJobs } ...

showcasing products from database with the help of Angular 12

Here are the files related to the item: Item file And here is the component file: Component file Lastly, this is the data service file: Data Service file However, issues arise when testing the code with console log statements as it indicates that the ...

Tips for displaying HTML content using an array in Vue JS

Hi, I'm a beginner with Vue JS and I'm working on passing an HTML table using this array. I have a dropdown where I can select the option I want, but I'm struggling to figure out how to include HTML within it. Whenever I try, it ends up disp ...

Issue with redirect using Node.js promise

I’ve created a settings page where users can add and remove filters. To handle the deletion process, I’ve implemented this jQuery function: $('#delete-filter').click(function (e) { var filtername = $('#filter-list').val(); ...

Removing an element from an object using ng-model when its value is empty is a standard practice

Utilizing the $resource service to access and modify resources on my API has been a challenge. An issue arises when the ng-model-bound object's value is set to empty - the bound element is removed from the object. This results in the missing element ...

The JQuery category filtering feature malfunctions when a category consists of more than two words

Utilizing Jquery, I have implemented a feature that displays project categories and allows users to filter projects based on the selected category. To view the code pen for this implementation, please click here: https://codepen.io/saintasia/pen/dzqZov H ...

Ensure that you patiently wait for the axios method to finish execution before moving on to the

I am currently learning vue.js and struggling with the concept of promises. I need to initialize a variable with data from an API call, but I want to ensure that the Axios call is generic: { data: { list: [], }, methods: { ShowList: function ...

Retrieve the page dimensions from a Material UI component `<DataGrid autoPageSize/>`

When utilizing <DataGrid autoPageSize/>, as outlined in the documentation, you can have a Material UI table that adjusts its page size based on the browser height. However, if you are fetching data from the server progressively, it becomes essential ...

Certain cases will see success with iPhone jquery/ajax functionality, while others may encounter

I am facing an issue with multiple pages in my project that utilize AJAX to submit a form to django. While the buttons work perfectly on various platforms and browsers like Chrome, Firefox, and desktop Safari, they seem to malfunction specifically on mobil ...

transferring data from ejs template

In my app.js file, I have an array that stores files. To display these files on a website, I use a for-loop in ejs: <% for(let i = 0;i<posts.length; i++){ %> <li class="listtitle"> <%= posts[i].title %> </li> ...

An issue has been detected by Zone.js where the ZoneAwarePromise `(window|global).Promise` has been unexpectedly replaced

I have recently integrated the Angular2 quickstart code into my existing webpack setup, but I seem to be facing an issue where something is interfering with the promise from zone.js, resulting in an error. Based on my research on Stack Overflow, it appears ...

Invoke the click handlers consecutively following the initial click handler using ajax requests

I have a button on my webpage that triggers multiple click events. The button code looks like this: <input type="button" id="myButton"/> There are several functions bound to the button's click event using jQuery: $("#mybutton").on("click", f ...

Encountered an unexpected token '{' error in Discord.js and Node.js integration

let user = message.mentions.users.first(); if (message.mentions.users.size < 1) return message.reply('Please mention someone to issue ARs.').catch(console.error); mcash[${user.id}, ${message.guild.id}].mc ...

What could be causing a template value in my AngularJS/Ionic Framework code to not be replaced properly?

Recently, I've been exploring the world of Ionic Framework with Angular by my side. However, I've hit a bit of a roadblock. My goal is to set up tabs at the bottom of my application using a model definition. Here's what I've tried so ...

The argument labeled as 'State' cannot be assigned to a parameter labeled as 'never'

I've recently delved into using TypeScript with React. I attempted to incorporate it with the React useReducer hook, but I hit a roadblock due to an unusual error. Below is my code snippet: export interface ContractObj { company: string; ...