Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function to convert decimal years value into years, months and days

Tags:

javascript

I need a function to transform decimal values of years in years, months and days. Ex: 1.5 years = 1 year, 6 month. 2.2527397260273973 years = 2 years, 3 months and 1 day.

I started with this function:

function yearsToYearsMonthsDays(value){
var years = Math.floor(value);
var months =  Math.floor( (value - years) /(1/12) );
var days = Math.floor ( ( (value - years) /(1/12) - Math.floor((value - years) /(1/12)) ) / (1/365) );
var result = years + " years, " + months + " months, " + days + " days";
    Logger.log(result);
}

But sometimes it doesn't work (ex: 0.75 doesn't produces 9 months).

Any help?

like image 923
craftApprentice Avatar asked Dec 18 '25 13:12

craftApprentice


1 Answers

I think the best way would be to change all to days, for example:

function yearsToYearsMonthsDays(value)
{
    var totalDays = value * 365;
    var years = Math.floor(totalDays/365);
    var months = Math.floor((totalDays-(years *365))/30);
    var days = Math.floor(totalDays - (years*365) - (months * 30));
    var result = years + " years, " + months + " months, " + days + " days";
    Logger.log(result);
}
like image 64
jorgeregidor Avatar answered Dec 20 '25 03:12

jorgeregidor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!