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

后端 未结 4 1666
我在风中等你
我在风中等你 2021-01-14 10:48

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.

4条回答
  •  旧巷少年郎
    2021-01-14 10:56

    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);
    }
    

提交回复
热议问题