Can Moment.js be used to calculate the difference in years and months between two dates?

Currently, I am calculating the difference between two dates in months using this code:

_result = Math.abs(moment(date1).diff(moment(date2), 'months')) + 1;

This code returns an integer representing the duration in number of months. Now, I would like to change the output format to display exactly as follows:

2 years, 3 months

If the year or month value is 1, then the format should be:

1 year, 1 month

How can I modify my code to achieve this desired result?

NOTE: I currently have the value in months, but I can easily convert it to days or years. However, the challenge lies in formatting the output to include both years and months as mentioned above.

Answer №1

To get the result in years and months, division and remainder functions can be utilized.

var totalMonths = 37;
var years = Math.floor(totalMonths / 12);
var months = totalmonths % 12;

finalResult = years + " years, " + months + " months";

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

Updating certain fields in AngularJS with fresh data

I am facing a challenge with the following code snippet: <div ng-controller="postsController"> <div id = "post_id_{{post.postid}}" class = "post" ng-repeat="post in posts"> ...... <div class="comments"> < ...

Looking to retrieve HTML elements based on their inner text with queryselectors?

I am looking to extract all the HTML divs that contain specific HTML elements with innerText = ' * ' and save them in an array using Typescript. If I come across a span element with the innerText= ' * ', I want to add the parent div to ...

JavaScript click or text-to-speech

Currently, I am working on a web application that is designed to automatically read text. Below is the code snippet that I am using: function hablalo() { var palabra = new SpeechSynthesisUtterance('Casilla 6 turno E18'); palab ...

The fs.fsync(fd, callback) function in the node.js API allows you

Can you explain the purpose of fs.fsync(fd, callback) in the Node.js API? fs.fsync(fd, callback) This function is used for asynchronous fsync(2). The completion callback only returns an exception if there is one. fs.fsyncSync(fd) This function is for ...

Activate the Jquery-ui Tooltip with a click event

Here is the code I'm using: function DrawTipsProgress(postid, ajaxurl) { var data = { action: 'ajax_action', post_id: postid } jQuery('#dashicon-' + postid).on("click", function () { jQuery.p ...

Having trouble with adding data from an array of objects to an HTML element using jQuery's each method

I am currently facing an issue with looping through an array of objects using $.each in jQuery and trying to append the values to an <li>. Here is the relevant jQuery code: $(".sidebar").empty().append("<div>" + "<h5>Student Info</ ...

The b-link component in bootstrap-vue is not displaying the text content or inner HTML as expected

Having trouble retrieving the textContent from a blink element and modifying it. Interestingly, when attempting the same process with a tag or div tag, it works without any issues. <b-link :ref="index" v-b-toggle="`${index}`" @c ...

Using Javascript regex to capture the image name from a CSS file

As I work with JavaScript regex, my goal is to extract the image name and extension as a capture group of CSS properties. Criteria Must start with "url" Followed by brackets Optional quotes inside brackets The location can include path information Must ...

Pass an array of links from the parent component to the child component in Vue in order to generate a dynamic

I am currently working on building a menu using vue.js. My setup includes 2 components - Navigation and NavLink. To populate the menu, I have created an array of links in the App.vue file and passed it as props to the Navigation component. Within the Navig ...

Arranging an array of objects in typescript with elements implicitly having an undefined type

Currently, I am facing a challenge where I need to sort an array of objects within a function. The catch is that the function receives the key as a parameter, making it unknown: export interface ProductsList { id: boolean nome: string qtde: number ...

The javascript file is unable to detect the presence of the other file

I am facing an issue with two JavaScript files I have. The first one contains Vue code, while the other one includes a data array where I created the 'Feed' array. However, when trying to output a simple string from that array, the console throws ...

The jQuery placeholder plugin encounters an error stating 'jQuery is not defined'

Having an issue on this specific page where I keep encountering a 'jQuery is not defined' error in both Chrome and IE because of the jQuery placeholder script. The declaration of jQuery comes before the plugin script. Checked for any conflicts ...

Tips for eliminating additional white space within a bootstrap row

I'm having trouble removing the extra space on my website while using Bootstrap 5. I've tried various Bootstrap classes like pr-0, mr-0, p-auto, m-auto but none of them seem to work. I also attempted using CSS margin-right: 0; but that didn' ...

Unable to display Polygon using ReactNativeMaps

Having trouble displaying the polygon correctly on my screen. I suspect it's due to receiving an array of objects from my API. This is the code snippet in question: <MapView.Polygon coordinates={poligonofinale} strokeColor="#000" fillColor= ...

Transforming a group of JSON objects into a two-dimensional array

Below is an array of JSON objects: var data = [{ 1: { name: 'Name 1', id: 'one' } }, { 2: { name: 'Name 2', id: 'two' } }]; I want to transform this into a 2-D array like this: var newData ...

Deleting an item from a Vue.js list

I'm currently working on a project to develop a basic webpage that allows users to add or remove textboxes using vue.js. new Vue({ el: "#app", data() { return { list: [] }; }, methods: { deleteFromList(index) { this ...

What is the best way to incorporate component-specific CSS styles in React?

This is the layout that I am attempting to replicate (originally from react-boilerplate): component |Footer |style.css |Footer.js In Footer.js, the styles are imported in a very elegant manner like this: import React from 'react'; im ...

Material-UI web application experiencing crashes due to worn-out cards, resulting in element type being declared as invalid and raising an error

After reviewing numerous similar SO questions, it appears that the issue always comes down to problems with imports. Typically, these involve mistyped import destinations or missing braces, but I have double-checked and found no such issues in my code. ht ...

Upcoming 13.4 Error: NEXT_REDIRECT detected in API routes

Here is the code snippet from my /app/api/auth/route.ts file: import { redirect } from 'next/navigation'; export async function GET(req: Request) { try { redirect('/dashboard'); } catch (error) { console.log(error); ...

How can we troubleshoot webdriver cucumber when test steps are skipped due to passed arguments?

Greetings! I have a feature file outlined below in my cucumber webdriver test project: # language: en Feature: Simple Test, Int and Prod Origin vs non origin checks Simple cloud environment Checks @javascript @EnvCheck Scenario: Check Env TEST Orig ...