How to calculate time difference in Angular from current time

When fetching data from firebase, I want to know how to calculate the difference between the fetch time and the current time.

For example:

if(this.data.time - current time <= (less or equal to) 3 hours) {
  console.log('Please wait till difference')
}

If the difference between data.time and current time is less than or equal to 3 hours, I want to log the time left within 3 hours.

The timestamps are in seconds and nanoseconds.

https://i.sstatic.net/MUflU.png

Let me provide further clarification. For instance, if the data time is 2:30 AM and the current time is 3:30 AM, it hasn't been 3 hours yet so I need to display 2 hours remaining. If the current time reaches 6:30 AM, then simply log that the time has exceeded 3 hours.

I'm having issues with this code showing an error "Type 'string' is not assignable to type 'number'."

secondsToHHMMSS(totalSeconds: any): string { // taken from https://stackoverflow.com/a/1322798/6513921
  let hours = Math.floor(totalSeconds / 3600);
  totalSeconds %= 3600;
  let minutes = Math.floor(totalSeconds / 60);
  let seconds = totalSeconds % 60;

  // for strings with leading zeroes:
  minutes = String(minutes).padStart(2, "0"); // encountering an error of String
  hours = String(hours).padStart(2, "0"); // encountering an error of String
  seconds = String(seconds).padStart(2, "0"); // encountering an error of String

  return (hours + ":" + minutes + ":" + seconds); 
}

const timeDiff = Math.floor(Date.now() / 1000) - lastLogin.seconds;
if (timeDiff <= 10800) {
  console.log("3 hours haven't elapsed yet.");
  console.log("Time remaining: " + this.secondsToHHMMSS(timeDiff));
}

Answer №1

Your timestamp lastLogin.seconds is using a format known as Epoch time.

To determine if the difference between your current timestamp, calculated with Math.floor(Date.now() / 1000), and your stored timestamp is less than 10800 seconds (3 hours), you can use the following code snippet:

secondsToHHMMSS(totalSeconds: any): string { // Utilizing Stack Overflow method
  let hours = Math.floor(totalSeconds / 3600);
  totalSeconds %= 3600;
  let minutes = Math.floor(totalSeconds / 60);
  let seconds = totalSeconds % 60;

  // Adding leading zeroes to minutes, hours, and seconds
  minutes = String(minutes).padStart(2, "0");
  hours = String(hours).padStart(2, "0");
  seconds = String(seconds).padStart(2, "0");

  return (hours + ":" + minutes + ":" + seconds); 
}

secondsToHHMMSSRegex(seconds: any): any { // Utilizing Stack Overflow method
    const date = new Date(1970,0,1);
    date.setSeconds(seconds);
    return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}

const timeDiff = Math.floor(Date.now() / 1000) - lastLogin.seconds;
if (timeDiff <= 10800) {
  console.log('Not yet 3 hours have passed.');
  console.log('Time remaining: ' + this.secondsToHHMMSSRegex(timeDiff));
}

Please note that reversing this conversion may slightly delay the results due to multiple division operations being performed, which can cause a discrepancy of a few seconds compared to your expectations.

Answer №2

Responding to your query,

If this.data.time represents time in seconds, you may utilize Date.now() for current time in milliseconds and then convert it to seconds by dividing by 1000.

We can easily compare the time difference with our desired number of hours (3600 seconds per hour).

const currentTime = Date.now() / 1000;

if(this.data.time - currentTime < 3 * 3600) {
  console.log("Please wait until the time difference is appropriate.")
}

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

`Error importing react-markdown in Next.js 11.1 with TypeScript``

Having trouble with importing react-markdown in my next.js SSG project. When running npm run dev, I encounter an error that prevents me from proceeding to test in next export. I understand that react-markdown is an esm package, but I'm not sure how t ...

Ways to prevent a single element from being included in the selection of the entire

Here is my question: I am facing an issue with a context menu that should only disappear when clicking outside of a specific row within that menu. The element I want to exclude, with the id "except", is buried deep within multiple parent elements in my co ...

Dealing with header types in Axios and Typescript when using Next.js

I successfully set up a next.js application with JWT authentication connected to a Spring Boot API (Next is used as a client). The implementation of the next.js app was influenced by this tutorial: Key Dependencies: Axios: 0.24.0 Next: 12.0.7 React: 17.0. ...

The formControlName inside a loop causes issues with the functionality of Angular's custom-control-input

I am looking to customize the theme style on Angular, but the checkbox is not behaving correctly. The following code worked well for me: <tr *ngFor="let item of lists let i=index" [formGroupName]="i"> <td> <d ...

Execute a function in Angular 9 whenever a variable undergoes a change in value

There are numerous versions of this question, many containing excessive and irrelevant details. Take into consideration the following scenario in a globals.ts file interestingString:string = 'blah'; now in a neighboring component neighbor.ts fil ...

Customize the border color of a dynamic textbox with Angular

I'm using Angular to create dynamic textboxes. <span *ngFor="let list of lists[0].question; let i = index"> {{ list }} <input type="text" *ngIf="i != lists[0].question.length-1" [(ngModel)] ...

Angular material: issue with alignment of table inside mat-expansion compared to other table

Hey there, I've encountered an issue on an Angular website where the columns in a table are not aligning properly. Does anyone have a solution for this problem? Thanks! <div class="table-responsive "> <table class="table" style=" ...

Having trouble with Angular redirecting to the incorrect URL?

Currently delving into the world of Angular, I am eager to create a straightforward application where users can effortlessly switch between two components. The issue arises when attempting to navigate back from the navbar to the login component: <a rout ...

Utilize ngbTabSet to position nav-pills within the card-header and tab-content within the card-body

I need help figuring out how to place nav-pills in card-header and tab-content in card-body using ngbTabSet. I have tried multiple methods but haven't been successful so far. Below is an example of what I am trying to achieve (using bootstrap.js) ht ...

Vercel Deployment Experiencing Timing Out Issues with Firebase Realtime Database Requests, Local Environment Works Fine

I'm facing an issue while trying to make requests to my Firebase Realtime Database from a Vercel-deployed application. The requests are successful in my local development environment, both in development and production modes. However, once deployed on ...

What is the best way to implement line-through text decoration for a list item when it is clicked in an Angular application? Additionally, how can the "completed" value in

<h1>My Exciting To Do List</h1> <input #newTask> <button (click)="addTask(newTask.value)">Add Task</button> <ul> <li *ngFor="let task of tasks">{{task.name}}</li> </ul> export cl ...

Using angular in combination with razor for implementing cookie-based authentication

Embarking on a new project with Angular 7, Asp.net core 2, Asp.net Identity, and IdentityServer4. In summary, the architecture of my project is structured as follows: A web API project (resource server) Data access layer project (C# project library) Ide ...

Error message stating: "The 'MktoForms2' property is not recognized within the scope of 'Window & typeof globalThis'."

Encountering the following error message: (Property 'MktoForms2' does not exist on type 'Window & typeof globalThis') while working with react and typescript useEffect(() => { window.MktoForms2.loadForm("//app-sj11.marke ...

Replay subscription in Angular 2 using RxJS 5, triggering the schedule based on the previous result

Within my Angular 2 application written in typescript 2, a server query is made to retrieve a value that requires regular updates based on an expiration date provided by the server. I am facing difficulties in creating an Observable stream that will autom ...

Save geometric shapes data in the SQLite database

How do I go about storing polygon data in an SQLite database? Important: I am utilizing the Cordova plugin. polygon: Point[]; interface Point { x: number; y: number; } https://i.sstatic.net/5EYf2.png ...

The getStaticProps function in Next.js fails to execute, causing an error to appear during the next build process

import { medusa } from "@/app/requests/medusaClient"; import { useState, useEffect, JSXElementConstructor, PromiseLikeOfReactNode, ReactElement, ReactNode, ReactPortal } from "react"; import { Product} from "@/app/models/productMod ...

Issues encountered when using PrimeNG tree select component with filter functionality

After successfully implementing the new primeng treeselect component with selection mode as "checkbox," I encountered an issue when trying to add a [filter]="true" as shown in the PrimeNG demo. <p-treeSelect [(ngModel)]="selectedNode1" [options]="nodes1 ...

Avoid using csurf with express.js and angular, instead use a token to protect your secret

Currently, I'm deep into a project involving express.js and angular. I followed the instructions in the README file on https://github.com/expressjs/csurf to implement csurf. While debugging through the source code of csurf, I observed that the secret ...

Ways to showcase corresponding information for an item contained within an array?

I'm working with a function that is designed to retrieve specific descriptions for objects nested within an array. The purpose of the function (findSettings()) is to take in an array (systemSettings) and a key (tab12) as arguments, then use a switch s ...

Generate TypeScript type definitions for environment variables in my configuration file using code

Imagine I have a configuration file named .env.local: SOME_VAR="this is very secret" SOME_OTHER_VAR="this is not so secret, but needs to be different during tests" Is there a way to create a TypeScript type based on the keys in this fi ...