function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jesus GJesus G 

Use moment.js to calculate difference between 2 dates


I would need to calculate the difference between 2 dates in years, months and days, and considering the difficulty to have a precise value by using the available functions and classes, I wondered if it would be possible to get the result by using moment.js.

The idea is to have 2 custom date fields and use moment.js to determine the difference between them in a format similar to 'x Years, x Months and x Days' when any of the values change.

Many thanks!
Arun ParmarArun Parmar
Hi Jesus G,

you can do using this, convert your date in [yyyy,mm,dd] format and use following script-

var date1 = moment([2016, 10, 30]);
var date2  = moment([2015, 01, 07]);

var years = date1.diff(date2, 'year');
date2.add(years, 'years');

var months = date1.diff(date2, 'months');
date2.add(months, 'months');

var days = date1.diff(date2, 'days');

console.log(years + ' years ' + months + ' months ' + days + ' days');

Thanks and regards
Jesus GJesus G
Many thanks for your reply Arun.

I already figured out that part of the code and my question is more about how to automatically run the script when any of the 2 custom fields change. I will have another look and post an update if I manage to solve it.