Code to calculate years month days

Hi guys

I have successfully implemented this code: (yay!!)
$w.onReady( function () {
$w(‘#dataset1’).onReady( () => {
$w(‘#repeater1’).forEachItem( ($w, itemData, index) => {
var dobms = (itemData.clientSince)
var nowms = Date.now();
var age = Math.floor((nowms - dobms) / (365.25 * 24 * 60 * 60 * 1000));
$w(“#text47”).text = age.toString();
})
});
} );

and it produces this as a result:
‘Length of time as client: 2.’

but what I would like is to see the calculation in years, months and days.

Anyone know the in-depth code for this? I’m a bit lost. I would like the final outcome to look like this:
Length of time as client: 2y 5m 4d.
Oh also to spoil myself if the person has been a client less than a year the outcome would simply look like this: 5m 4d.

Thanks!!

You can use something like this:

let startDate = new Date("2017-02-03T00:00:00Z");
var now = new Date();

let d = Math.abs(now - startDate) / 1000;
let results = {};
let options = {
    year: 31536000,
    month: 2592000,
    day: 86400
};

Object.keys(options).forEach(function (key) {
    results[key] = Math.floor(d / options[key]);
    d -= results[key] * options[key];
});

let string = "length of time: ";
if (results["year"] > 0) string += results["year"] + " years ";
if (results["month"] > 0) string += results["month"] + " months ";
if (results["day"] > 0) string += results["day"] + " days ";

console.log(string);

You can customize this based on your needs.

Good luck

As a plus, here’s function that should work as you wish:

 
function dateDifference(diff) {
 var str = '';
 var values = [[' year', 365], [' month', 30], [' day', 1]];
 for (var i=0;i<values.length;i++) {
 var amount = Math.floor(diff / values[i][1]);
 if (amount >= 1) {
       str += amount + values[i][0] + (amount > 1 ? 's' : '') + ' ';
       diff -= amount * values[i][1];
    }
  }
 return str;
}

Ps: You only have to pass number of difference days.
Best,

Mustafa

1 Like