Calculate the time difference between two dates using Moment JS

I have two specific dates that I need to calculate the duration between in a specific format ${y}year ${w}weeks ${d}days

In order to achieve this, I have created a function. Here is the code snippet:

 setTotalDuration(): void {
    const formattedFrom = moment(this.startDate).format('YYYY-MM-DD HH:mm:ss');
    const formattedTo = moment(this.endDate).format('YYYY-MM-DD HH:mm:ss');
    const duration = moment.duration(moment(formattedTo).diff(moment(formattedFrom)));
    const y = Math.floor(duration.asYears());
    const w = Math.floor(duration.asWeeks() - y * moment().weeksInYear());
    const d = Math.floor(duration.asDays() - w * 7);
    this.totalDuration = ` ${y}year ${w}weeks ${d}days`;
}

Despite my effort, it seems that the function is not working correctly. For example, when I input startDate as 19/02/2020 and endDate as 19/02/2021, instead of getting the desired result of 1 year 0 weeks 0 days, I am getting 1 year 1 week 373 days. This is not what I intended.

Can anyone help me identify where the issue might be?

Answer №1

I trust this meets your expectations. Calculate the variance in years and add it to the original date; then determine the difference in weeks and add that to the starting date once more.


var moment = require("moment");

var x = moment(["2021", "02", "20"]);
var y = moment(["2020", "02", "19"]);

var yrs = x.diff(y, "year");
y.add(yrs, "years");

var wks = x.diff(y, "week");
y.add(wks, "weeks");

var dys = x.diff(y, "days");

console.log(yrs + " years " + wks + " weeks " + dys + " days");


Explore further: https://codesandbox.io/s/compassionate-bas-fg1c2

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

Transform a PHP array into a JavaScript array with UTF-8 encoding

I am currently facing an issue with a products table that contains foreign characters. My goal is to utilize a PHP array in JavaScript to filter a dropdown box as the user types. Everything seems to be working fine except when encountering foreign characte ...

Aligning a picture at the center of the screen with CSS - Various screen and image sizes

For my project, I need to design a web page with a single image perfectly centered both vertically and horizontally on the screen. Here are the specific requirements: The client's screen size is unknown (mobile) The image will be user-defined with u ...

Using the PUT method in Node.js to set the ID

Need help with setting ID value from frontend apiRoutes.put('/intake', function(req, res) { Intake.findById({id, function(err, intake) { if (err) res.send(err); check : true; intake.save(function(err) { ...

Using React and Typescript: Populating an array within a For Loop using setTimeout is not happening sequentially or at all

I'm currently working on a function that animates images of random cars moving across the screen. My goal is to stagger the population of the "carsLeft" array using setTimeout, where I will eventually randomize the delay time for each car. Everything ...

Calculate the total sum of input values using jQuery

Here is the HTML I've been working with: I am trying to create a script where one textbox will display the total amount, and another textbox will display the following data: "name": [{ "id": 3, "qty": 2 }, { "id": 4, "qty": 5 }] Here's ...

Freemarker substitute & and &ampersand;

I am facing an issue with Freemarker. I need to eliminate all the special characters from this sentence as well as from similar sentences in the future: BLA BLA RANDOM &, RANDOM BLA In particular, I want to remove the & character. The platform ...

combine two arrays of observations into a unified array of observations

One challenge I am facing is merging two Observable arrays in Angular without using the subscribe method. How can this be achieved? My approach so far has been as follows: this.similarIdeasObservable$.pipe(concat(this.ideaService.getSimilarIdeas(this.id ...

Why is the current Menu Item highlight feature not functioning properly?

Why isn't the highlight current Menu Item feature working? I've checked my code, but it doesn't seem to be functioning as expected. Could you lend me a hand? Html: <section id="menu-container"> <div id="bar"><img src="b ...

The expected behavior is not displayed when using Async.waterfall within a promise queue

In our software implementation, we have utilized a promise queue feature using the q library. The sequence of functions is structured as follows: PQFn1 -(then)- PQFn2 - .... Within PQFn1, an array of values is passed to a callback function implemented wi ...

Retrieve the innerHTML contents from all span elements

I'm having trouble getting the content of all span tags that are child elements of div#parent. So far, I've only been able to retrieve the content of the first one. Can someone please assist me with this? $( document ).ready(function() { ...

Creating a typescript object shape without an index signature involves specifying the exact properties

I have a query regarding a potential design gap in TypeScript. Consider a function that accepts objects meeting a specific interface: interface Params { [key: string]: string | number | boolean | undefined | null; } This interface specifies that the k ...

Can the three.js library be used to display Finite Element Analysis (FEA) outcomes

In the process of developing a real-time wind turbine simulation Finite Element Analysis software using three.js to visualize the calculated 3D FEA results, I am faced with a challenge. The goal is to have the displayed 3D wind turbine rotate like its ph ...

Can you explain the distinctions among 'data:', 'data: ()', and 'data()' when working with Vue.js?

While exploring the Vue.js documentation, I came across two ways to define data: data: {} and data() { return; }. data: { defaultLayout: 'default' } data() { return { defaultLayout: 'default' } } However, there is ...

Guide on accessing device details with Angular2 and Typescript

I'm working on populating a table with details using TypeScript, but I need some assistance. 1. Device Name 2. Device OS 3. Location 4. Browser 5. IsActive I'm looking for a solution to populate these fields from TypeScript. Can anyone lend me ...

Avoid the problem of animations triggering twice when clicking

Hey there, I am facing an issue with my slider. If you could take a look at this website , you will notice that after clicking on the arrows, the slider behaves asynchronously. It changes speed rapidly at times and then slows down, repeating this pattern ...

The Angular Reactive Forms error message indicates that attempting to assign a 'string' type to an 'AbstractControl' parameter is invalid

While attempting to add a string value to a formArray using material forms, I encountered the following error message: 'Argument of type 'string' is not assignable to parameter of type 'AbstractControl'.' If I try adding a ...

Having trouble displaying an array in React by using Array.map()?

My code used axios to retrieve an array of usernames and then utilized setState to update the state. I checked the users array in console.log to confirm that it was indeed an array. axios.get("http://localhost:5000/users/") .then((res) =& ...

Is there a counterpart to ES6 "Sets" in TypeScript?

I am looking to extract all the distinct properties from an array of objects. This can be done efficiently in ES6 using the spread operator along with the Set object, as shown below: var arr = [ {foo:1, bar:2}, {foo:2, bar:3}, {foo:3, bar:3} ] const un ...

Simultaneously updating the states in both the child and parent components when clicked

In my code, I have two components: the parent component where a prop is passed in for changing state and the child component where the function is called. The function changes the state of the parent component based on an index. changeState={() => this ...

Removing Specific Items from a List in React: A Step-by-Step Guide

I have developed a basic ToDo List App. The functionality to display tasks from the input form is working correctly, but I am facing issues with deleting tasks when the Delete button is clicked. export class TaskList extends Component { constructor(pr ...