How can I calculate the number of months and days left between two dates using JavaScript?

I need help calculating the number of months and remaining days between two dates.

For example:

start = 2017-04-10, end = 2017-05-15

The desired output should be 1 month, 5 days

-

This is my approach: Calculating number of months:

var numOfMonths = end_month - start_month + (12 * (end_year - start_year));
if(end_day < start_day){
 numOfMonths--;
}

And for the days:

var numOfDays = (end - start) / (1000 * 60 * 60 * 24)

The current output shows as 1 month, 35 days.

How can I adjust the calculation to remove the days associated with a full month, and only display the remaining days?

Answer №1

Check out this innovative solution utilizing Moment.js:

let calculateDifference = (startDate, endDate) => {
    let years, months, days;
    
    startDate = moment(startDate);
    endDate = moment(endDate);
    
    years = endDate.diff(startDate, 'year');
    startDate.add(years, 'years');

    months = endDate.diff(startDate, 'months');
    startDate.add(months, 'months');

    days = endDate.diff(startDate, 'days');

    return {
      days: days,
      months: months,
      years: years
    };
  },
  formatDifference = d => `${d.years} years, ${d.months} month, ${d.days} days`;

// Example comparisons
let diff1 = calculateDifference('2017-04-10', '2017-05-15');
console.log('diff1:', formatDifference(diff1));

let diff2 = calculateDifference('2017-04-10', '2017-05-09');
console.log('diff2:', formatDifference(diff2));

let diff3 = calculateDifference('2017-04-10', '2017-06-15');
console.log('diff3:', formatDifference(diff3));

let diff4 = calculateDifference('2015-01-22', '2017-06-15');
console.log('diff4:', formatDifference(diff4));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

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

Utilizing array indices/variables for dynamic labels on an Animated Google Bar Chart

My database contains multiple tables, and I am looking to utilize Google Charts to display this data. I want the chart to have smooth animations, so I came across a helpful code snippet that I found online and am currently tweaking it to fit my needs. Sin ...

Alter the default time zone in JavaScript

PHP features a function known as date_default_timezone_set which impacts the GMT time that is used by the Date() command. Is there a way for this function to also impact JavaScript? Here is a custom function I have: function calcTime(offset) { d = n ...

Having trouble setting up Strongloop for Loopback v.3 on macOS Catalina?

I'm currently in the process of understanding Loopback v3 (which is being utilized on a project site where I'm actively involved), and I'm attempting to follow the tutorials provided. One of the crucial steps involves installing Strongloop ...

What causes the slow loading of a div from an external URL?

I have created two buttons that open different PHP pages. When I click on one button, it loads the respective URL into a div. However, when switching to the other button, there is a noticeable delay in loading the new page. The transition between buttons ...

Struggling with conditionally rendering components or elements in React while managing state

I am currently working on a react login/signup form where the user lands on the signup section by default. My goal is to display the login section when the user clicks on the login button and show the products section when the user clicks on "Get Started" ...

Unable to complete 'drawImage' operation in react-image-crop

I'm currently working on cropping an image with the 'react-image-crop' package and storing the output in the result variable. import React, { useState } from 'react' import ReactCrop from 'react-image-crop' import ' ...

The API has been triggered twice

I am currently working on a React component where I have implemented an API call using the useEffect hook with an empty dependency array. However, I noticed that the API is being called twice and I can't seem to find the reason behind it. import { use ...

The THREE.js GLTFLoader is failing to load the 3D model

Hey there, I'm encountering an issue with displaying a 3D model using THREE.js GLTFLoader(). Below is the script I am working with: Here is the HTML file: <!DOCTYPE html> <html lang="en"> <head> <meta charset=&quo ...

Is there a way to turn off the pinch-to-zoom trackpad gesture or disable the Ctrl+wheel zoom function on a webpage

Take a look at this example - While zooming in on the image by pressing ctrl + scroll, the image zooms but the page itself does not scale. Only the image is affected by the zoom. I am attempting to replicate this functionality on my Next.js page. I have ...

Is AngularJS the new way to implement DOM manipulation similar to JQuery?

Many tutorials and articles advise against including jQuery in an Angular.js project to ensure a smooth transition. However, what are some alternatives for simple DOM manipulations such as changing CSS properties without using jQuery? Is it possible to a ...

What is the process for retrieving data through a server-side API request?

I have been working on setting up my API URL in my Node.js backend application. I initially passed the entire URL in my frontend AJAX call, but now I want to transition to a server-side API call to avoid exposing the URL. Since I am not very experienced wi ...

The method is unable to assign a value to the undefined property 'var'

I am encountering a simple issue that is giving me an error message TypeError: Cannot set property 'question' of undefined at setQuestion I am struggling to identify the root cause of this problem. As I am new to AngularJS, I wonder if ...

What is the best way to add unique styles to multiple tags with the same class designation?

Looking for suggestions on styling two tags with the same class differently? I have 2 tables: <table id="tab1" class=".ui-jqgrid .ui-jqgrid-hbox"> <table id="tab2" class=".ui-jqgrid .ui-jqgrid-hbox"> The first table is a jqgrid on the page, ...

Challenges regarding placement and z-index are causing issues

Currently, I am attempting to make the menu overlap the content on my webpage. However, I am facing an issue where it moves the content box instead of overlapping it. I have already experimented with the position: relative concept, but unfortunately, the ...

Conceal navigation buttons on the first and last pages of the slider

I'm attempting to develop a slider that hides the "previous" button when it is on the first slide and hides the "next" button when it reaches the last slide. The slider will be created using a combination of PHP, forms, and JavaScript. Below is the H ...

Content Security Policy (CSP) recommendations for CSS files that are

I am facing an issue where a third-party JavaScript file is being loaded into my application, which then injects an iframe onto the page. This iframe subsequently loads its own JavaScript that creates an inline style tag in the parent window. Due to this ...

Methods for delivering static resources on multiple routes in Express JS

Is there a way to effectively serve static resources for all routes in Express JS? I attempted to serve files with static resources using the following code snippet: app.use(Express.static(`${this.PATH}`)); app.use(Cors()); app.use(Express.json()); app.g ...

The function to set the state in React is malfunctioning

I'm currently in the process of developing a website where I utilize fetch to retrieve information and display it to the user. Initially, I opted to save this data in a state variable, but for some reason, it's not functioning as expected. Upon ...

Guidelines for duplicating an object into three separate objects with underscore.js

Hey there, I receive my JSON data as an object in the following format: { "id": "001724", "select": false, "class": "product", "Names": [ "A", "B", "C" ], "available": true, ...

"Surprising results encountered when using the filter method in JavaScript Arrays

Scenario During a recent job interview, I was given a coding test: var array = [1, 2, 3]; array[10] = 10; alert(array.filter( n => n === undefined)); I confidently expected the alert to show an array with 7x undefined values, or something similar. ...