Search code examples
javascriptdate

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) is returning something like 6 months 3 days.


Solution

  • 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; 
    }
    
    //==== examples ========
    
    console.log(getFormatedStringFromDays(0));
    console.log(getFormatedStringFromDays(1));
    console.log(getFormatedStringFromDays(31));
    console.log(getFormatedStringFromDays(310));
    console.log(getFormatedStringFromDays(365));
    console.log(getFormatedStringFromDays(3100));

    Not the most elegant solution but it should work