What is the best way to calculate the number of days that have passed since a certain

Hey there, I've got this 10 Dec, 2019T14:07:21 date format from the backend. My goal is to determine how many days ago it was.

For example, today is the 20th, so if the date is today's date, it should show as 0 days ago.

Answer №1

Feel free to test out this snippet of code.

let startDate = new Date("01/01/2022");
let endDate = new Date("01/10/2022");
let daysDifference = parseInt((endDate - startDate) / (1000 * 60 * 60 * 24), 10); 
console.log(daysDifference)

Answer №2

If you want to compare two dates, you can subtract them to find the difference in milliseconds, which can then be converted into days.

const currentDate = new Date();
// Simulating a past date
const daysAgoDate = new Date();
daysAgoDate.setDate(daysAgoDate.getDate() - 10);
// Calculate the difference between the two dates in milliseconds
const timeDifferenceMs = currentDate - daysAgoDate;
// Convert the milliseconds to days
const daysDifference = Math.round(timeDifferenceMs / (1000 * 60 * 60 * 24));
console.log(daysDifference)

Answer №3

Calculate the number of days since December 10, 2019 at 14:07:21 by subtracting the current date from that date and converting the result to days.

Answer №4

When you're attempting to find the difference in days between two dates, it's referred to as "date diff". To achieve this, you must first create a new Date object from the string representing the dates. One way to do this is by utilizing the Moment.js library, which can parse the date string and return a Date object.

var date1 = moment("10 Dec, 2019T14:07:21", "DD MMM, YYYY");
var date2 = new Date() //today date

A handy JavaScript function for calculating the date difference is provided below:

function dateDiff(date1, date2) {
    var datediff = date1.getTime() - date2.getTime(); 
    return (datediff / (24*60*60*1000));       
}

The dateDiff function will give you the difference between the dates; if date1 is in the past, it will return a negative number of days. To display the result in the format like "x days ago," simply multiply the result by -1.

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

Guidance on implementing a source map in a Node.js VM

Currently, I am analyzing JavaScript bundled source code in Node.js using the following snippet of code: const javascriptCode = "..." const javascriptSourceMap = "..." const wrapper = NativeModule.wrap(javascriptCode); const script = ne ...

Having trouble with Node.js utilizing Express and Cross-Origin Resource Sharing (CORS) after numerous

I have set up a Node.JS REST API with the CORS npm module, but I am facing an issue where the server hangs after making a small number of calls (around 6 or 7). I have tried using the CORS npm module with default settings and also manually setting it up as ...

Rules for validating string and numeric combinations in Vuetify are essential for ensuring accurate

Looking for guidance on implementing Vuetify validation to enforce rules (using :rules tag on a v-text-field) in the format of AB-12345678 (starting with two letters followed by a hyphen and then an 8-digit number). I'm having difficulty achieving thi ...

Is there a way to handle templates in AngularJS that is reminiscent of Handlebars?

Is there a way to handle an AngularJS template using a syntax similar to Handlebar? <script type="text/ng-template" id="mytemplate"> Name is {{name}} </script> I know how to retrieve the template using $templateCache.get('mytemplate&ap ...

Executing commands using the Node command line interface on Msysgit in Windows 10

Recently, I made the decision to start using Node on my personal laptop, which is running Windows 10. However, I have encountered an issue with the Node command line interface hanging when I attempt to run it. When I simply type node in the console, the i ...

Enhance the functionality of jQuery sortable by including additional details

I have a li list that I have implemented sortable functionality using jQuery. In order to ensure that the updated data is sent to the correct destination, I need to include some hidden values in the serialized data. How can I achieve this? HTML <ul i ...

Getting the ID name from a select tag with JavaScript - A quick guide!

Can you help me retrieve the id name using JavaScript when a selection is made in a select tag? I have tried running this code, but it only alerts undefined. For instance, if I select bbb in the select tag, I should be alerted with 2 Any suggestions on ...

What are the benefits of using Bower.js when npm is already functioning well?

When working in the main project directory, running the command npm init will create a file called "package.json". If I need to install dependencies such as angular, jQuery and bootstrap, I can use the following commands: npm install angular --save-de ...

Verifying if checkboxes are selected in PHP using JavaScript

echo '<div class="col-lg-10 col-lg-offset-1 panel">' . "<table id='data' class='table'> <tr> <th></th> <th>Document No</th> <th>AWB NO</th> ...

How to unselect a radio button in Vue using a button, similar to using vanilla JavaScript

Looking to translate this vanilla JavaScript code into Vue, here's the original: const radio = document.querySelector('#radio'); const boton = document.querySelector('#boton'); boton.addEventListener('click', () => { ...

What is causing the "unable to resolve dependency tree" error when using ng new newApp?

Struggling with creating a new Angular app using the command ng new app-name? When running the command, you may encounter the following error in the command line. Installing packages (npm)...npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve depen ...

Develop a program that retrieves necessary components, sets up, and launches a web browser

I am running an application with a node server and I want to achieve the following: npm start This should install both node dependencies and bower dependencies, and then open a browser window. Is it possible to do this without using gulp or grunt? Howe ...

What is causing my div exchange using .class to fail?

Struggling to convert this code from working with IDs to Classes. The code reveals one Div while hiding another based on the onClick event. Originally, it was straightforward because the div location was absolute. In the classes version, I need to revea ...

mongodb cannot locate the schema method within the nested container

Trying to access a method of a schema stored inside a mixed container has presented a challenge. The scenario is as follows: var CaseSchema = mongoose.Schema({ caseContent : {}, object : {type:String, default : "null"}, collision : {type : Boo ...

Adding a function into a node within PostgreSQL

Hi there, I'm currently following a tutorial and attempting to execute a simple insert query, however, I keep encountering a 404 error. I am using Postman to input values. function function insertUser(req, res, next){ req.body.users = parseInt(r ...

Tips for creating a static background when displaying a modal popup in AngularJS

Incorporating a modal popup to modify a row within a grid view has been my recent task. Leveraging the row.getProperty() function, I successfully extracted the row values within the modal. However, an inconvenience emerged when attempting to edit a value ...

Error: The command 'sudo npm install' could not be found

After setting up nodejs and npm on my Amazon AMI server using the node version manager, I am currently running node version 7.10.0 and npm version 4.2.0. The nodejs project is located in the var/www/testing folder. When attempting to install dependencies ...

Arrangement of watch attachment and $timeout binding

I recently encountered a component code that sets the HTML content using $scope.htmlContent = $sce.trustAsHtml(content). Subsequently, it calls a function within a $timeout to search for an element inside that content using $element.find('.stuff' ...

Encountering an issue while trying to install Angular CLI 7 on Mac operating system Mojave

Encountering issues while trying to install angular@cli on Mac Osx Mojave 10.14.5 with node version 10.15.3 and npm 6.9.0 After attempting to remove and reinstall node and npm, I followed the troubleshooting steps in this article Error installing angular/ ...

Syncing data between parent and child components in VueJS using v-bind:sync with an object parameter for bidirectional data flow

In the app I am developing, there is a main component that passes an Object, specifically this.form, to a child form component using v-bind:sync="form". The child form then emits values for each key of the parent object on @input events. My goal is to be ...