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

后端 未结 4 1664
我在风中等你
我在风中等你 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 11:01

    I stated using jorgeregidor's answer and I generalized it a bit.

    function years_to_ymdh(value) {
        console.log('initialy : '+ value + ' years');
    
        var results=[], rest=value;
        var units=['years', 'months', 'days', 'hours', 'minutes'];
        var converters=[1, 12, 365.25, 365.25*24, 365.25*24*60];
    
        units.forEach(function(d,i){
            if (i==0) results[i] = Math.floor(rest);
            else results[i] = Math.floor(rest * converters[i]);
            if (results[i] != 0) rest = rest % (results[i]/converters[i]);
            console.log('-'+results[i]+' '+d+' -> rest', rest);
        });
    
        var text = results.map( (d,i) => d+' '+units[i] ).join(', ');
        console.log(text);
    
        // return text;
        return results;
    }
    

    years_to_ymdh(2.2527397260273973)
    -2 years -> rest 0.25273972602739736
    -3 months -> rest 0.00273972602739736
    -1 days -> rest 0.000001875240265258784
    -0 hours -> rest 0.000001875240265258784
    -0 minutes -> rest 0.000001875240265258784
    2 years, 3 months, 1 days, 0 hours, 0 minutes

    To get seconds it's pretty easy to add 'seconds' to the units array and 365.25*24*60*60 to the converters array.

提交回复
热议问题