Calculating the number of days between two dates with angular

I need assistance with my application. I have an API response that includes a message sent date, and I am looking to calculate the difference in days between the current date and the date from the API response using Angular 8 along with map in ngFor.

Here is a link to my code on StackBlitz

Any help would be greatly appreciated. Should I consider using moment.js for this task?

Answer №1

To solve this issue, you may simply insert plain code like the following:

calculateDiff(dateSent){
    let currentDate = new Date();
    dateSent = new Date(dateSent);

    return Math.floor((Date.UTC(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate()) - Date.UTC(dateSent.getFullYear(), dateSent.getMonth(), dateSent.getDate()) ) /(1000 * 60 * 60 * 24));
}

Make sure to adjust your HTML in order to transmit the correct date information.

Here's an example for reference: https://stackblitz.com/edit/angular-bf5qer?file=src/app/app.component.ts

This code snippet was inspired by and might need some testing to ensure accuracy.

Answer №2

You can achieve the desired result without relying on momentjs.

Update:

If you want to take into account daylight saving time, avoid using getTime and opt for Date.UTC instead:

  calculateDiff(data){
    let date = new Date(data.sent);
    let currentDate = new Date();

    let days = Math.floor((Date.UTC(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate()) - Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) ) /(1000 * 60 * 60 * 24));

    return days;
  }

<div *ngFor="let data of responseData" class="dataHolder">
  <div>{{data.title}}</div>
  <div>{{data.type}}</div>
  <div>{{data.msg}}</div>
   Message sent on: <div>{{data.sent}}</div>
   <div style="font-weight:bold;">sent {{calculateDiff(data)}}_ days ago</div>
</div>

Previous Answer:

  calculateDiff(data){
    let date = new Date(data.sent);
    let currentDate = new Date();

    let days = Math.floor((currentDate.getTime() - date.getTime()) / 1000 / 60 / 60 / 24);
    return days;
  }

<div *ngFor="let data of responseData" class="dataHolder">
  <div>{{data.title}}</div>
  <div>{{data.type}}</div>
  <div>{{data.msg}}</div>
   Message sent on: <div>{{data.sent}}</div>
   <div style="font-weight:bold;">sent {{calculateDiff(data)}}_ days ago</div>
</div>

Answer №3

Here is a helpful example:

Live Demo

.html

<span style="color:red;">It has been {{calculateDaysAgo(data.date)}} days since it was sent</span>

.ts

calculateDaysAgo(sentDate) {
    var startDate:any = new Date(sentDate);
    var endDate:any = new Date();
    var differenceDays:any = Math.floor((endDate - startDate) / (1000 * 60 * 60 * 24));

    return differenceDays;
}

Answer №4

View the working demo here

<div style="font-weight:bold;">It has been {{calculateDiff(data.sent)}} days since this was sent</div>

ts file:

calculateDiff(sentOn){

    let todayDate = new Date();
    let sentOnDate = new Date(sentOn);
    sentOnDate.setDate(sentOnDate.getDate());
    let differenceInTime = todayDate.getTime() - sentOnDate.getTime();
    // To calculate the number of days between two dates
    let differenceInDays = Math.floor(differenceInTime / (1000 * 3600 * 24)); 
    return differenceInDays;
}

Answer №5

When working with your HTML, be sure to pass the dateString to the calculateDiff function.

<div style="font-weight:bold;">sent {{calculateDiff(data.sent)}} days ago</div>

In your TypeScript file, update your code as follows:

calculateDiff(date: string){
    let currentDate: Date = new Date();
    let previousDate = Date.parse(date); //time in milliseconds
    var timeDifference = currentDate.getTime() - previousDate;
    var differenceInDays = timeDifference / (1000 * 3600 * 24);
    return Math.floor(differenceInDays);
}

Answer №6

Check out this link for more information. Remember to input the date by using the function calculateDiff(data.sent)

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

An issue occurred during rendering: `TypeError: Unable to retrieve the length property of an undefined value`

I want to display an overlay only when there is text in my search input. Below is the template for my input field: Input.vue: <template> <div> <input v-model="query" class="input" placeholder="Global search..."></input&g ...

Managing asset paths post ng build: A guide

I've been attempting to use assets to display svg icons on my ESRI map. I'm working with Angular9 and the esri js api, trying to add a symbol from a URL. Locally, the svg appears on the map, but once I build and deploy the project to IIS, it sta ...

Difficulty encountered when choosing and interacting with website button with the utilization of Python 3.5.1 and Selenium 2.53.2

I am currently utilizing a Macbook Air that runs on OS X El Capitan. My tool of choice is Python IDLE, and I am attempting to target and interact with the button located on the webpage below: <div class="search-form-actions"> <button class="btn ...

How do you trigger a function in a child component that was imported when a parent element is clicked?

Is it possible to access and call a function in an imported component from the "parent element"? I have multiple modules that I want to include dynamically in my app. I thought that if I import a component like Header in my main App.vue file, it would reco ...

Executing several asynchronous functions in Angular 2

I am currently developing a mobile app and focusing on authentication. In order to display data to the user on my home page, I need to connect to various endpoints on an API that I have created. Although all endpoints return the correct data when tested i ...

Utilizing Javascript to retrieve the current Controller and Action in Rails

Is it possible for JavaScript to determine the current controller and action in Rails? I had the idea of creating a hidden container to store the current controller and action, but I'm curious if there is a specific JavaScript function for this purpo ...

The feature to Select/DeSelect All does not function properly when dealing with individual records

Here's the JavaScript code I'm working with: if (document.forms[0].Check_All.value=="Select All") { for (i = 0; i < chk.length; i++) { chk[i].checked = true; document.forms[0].Check_All.value = "DeSel ...

Guide to implementing a Page Object Model for improved debugging of Protractor tests

Introduction I am on a mission to streamline my e2e testing code using the Page Object Model for easier maintenance and debugging. My Approach When embarking on creating end-to-end tests with Protractor, I follow these steps to implement the Page Object ...

Tips on extracting the ID number prior to locating an element by its ID using Python Selenium

I am currently attempting to automate sending LinkedIn connection requests using Python with Selenium. However, I am facing an issue where the ember number value keeps changing every time I try to copy the id of the button. Sometimes it shows as #@id=" ...

Alert: Refs cannot be assigned to function components. Any attempt to access this ref will result in failure. Have you considered using React.forwardRef()? displayed in the @Mui Component

Is anyone familiar with this particular component? <Controller control={control} {...register("DOB", {})} render={({ field }) => ( <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePicker ...

What is the best way to stop event bubbling in react-router-dom when using the <Link> component?

Hey there! I have a situation that I need help with. I tried putting the Link around the whole post so that I could prevent bubbling for individual buttons, but for some reason stopPropagation() is not working as intended. Following advice from another s ...

Assigning a value to a variable from a method in Vue: a step-by-step guide

I'm having trouble assigning values from a method to variables in HTML. Here's what I have in my code: <b-card-text>X position {{xpos}}</b-card-text> <b-card-text>Y position {{ypos}}</b-card-text> I would like to assign v ...

Special function to handle ajax requests malfunctioning

I am seeking to develop a unique function for AJAX post requests. Below is the existing source code: function handleAjax(url, data) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.st ...

Unlock real-time alerts with the power of JavaScript and PHP!

I am currently working on enhancing my skills in javascript. I have a basic idea of what I want to achieve. My goal is to create an automated javascript function that accesses a php page. This php page will create an array of new notifications for the ja ...

The callback function in jQuery does not function properly in a custom class or object

Hello, I am new to the world of programming so bear with me if this question seems basic. I am currently working on creating a simple wave effect to give the illusion of moving water. Initially, I achieved this using a straightforward jQuery function which ...

Having trouble with Vue.js not returning HTML elements from methods properly?

I have been attempting to retrieve html elements from a method, and I thought of using v-html for this purpose (not sure if there is a better approach). However, I seem to have encountered an issue with backtick templates and string interpolation. An error ...

Prevent onlick actions until JavaScript function has completed

I run a dynamic quiz website using PHP, JavaScript, and MySQL. The quiz consists of multiple choice questions with answer options displayed on four buttons. <input type = "button" value="$alt1" onClick="changeQuestion('alternative1'); this.st ...

Adjust the tally of search results and modify the selection depending on the frequency of the user's searches within an array of objects

Seeking assistance with adding a new function that allows users to navigate to the next searched result. Big thanks to @ggorlen for aiding in the recursive search. https://i.stack.imgur.com/OsZOh.png I have a recursive search method that marks the first ...

Utilizing multiple conditions in MongoDB is a great way to filter results when a specific key

const filterCriteria = { carColor: req.query.carColor, languages: { $regex: `${req.query.languages}`, $options: 'i' }, incomeMonth: { $gte: req.query.incomeMonth }, incomeYear: { $gte: req.query.incomeYear }, ...

Encountering an error message stating "Unable to access property 'injector' as null when attempting to downgrade Angular 2 service."

Hello everyone, I could use some assistance with a particular issue I'm facing. Below is the code snippet from my angular 1.x app.js: angular.module('app', []); angular.module('app.test', ['app']) .config(($statePr ...