Helpha Helpha -4 years ago 39
Javascript Question

Transform number of days in Years-Months-Days in javascript

Hi I've been searching for a while now and I cant seem to find the answer to this.

I have to code a function in javascript that takes in a numbers of days in parameter and then transforms it into a more understandable string.

Ex :

function getFormatedStringFromDays(days)
{
var formatedString = "";
//... logic
return formatedString;
}


So getFormatedStringFromDays(183) would return something like 6 months 3 days.

Answer Source

Supposing that year contains 365 days and month - 30 days the answer could look as follows. Otherwise there should be more input params

function getFormatedStringFromDays(numberOfDays) {
    var years = Math.floor(numberOfDays / 365);
    var months = Math.floor(numberOfDays % 365 / 30);
    var days = Math.floor(numberOfDays % 365 % 30);

    var yearsDisplay = years > 0 ? years + (years == 1 ? " year, " : " years, ") : "";
    var monthsDisplay = months > 0 ? months + (months == 1 ? " month, " : " months, ") : "";
    var daysDisplay = days > 0 ? days + (days == 1 ? " day" : " days") : "";
    return yearsDisplay + monthsDisplay + daysDisplay; 
}

Not the most elegant solution but it should work

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download