本文介绍了Javascript函数将十进制年份值转换为年,月和日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个函数来转换年,月和日中年的十进制值.例如:1.5年= 1年零6个月.2.2527397260273973年= 2年零3个月零1天.
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.
我从此功能开始:
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);
}
但是有时它不起作用(例如:0.75不会产生9个月的时间).
But sometimes it doesn't work (ex: 0.75 doesn't produces 9 months).
有帮助吗?
推荐答案
我认为最好的方法是将所有日期都更改为天,例如:
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);
}
这篇关于Javascript函数将十进制年份值转换为年,月和日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!