我有一个计算功能,其中的一部分显示了实现目标所需的天数.
而不是仅显示我想要计算的天数和天数几个月或几天,几个月和几年,取决于数量.我有一个if语句的分裂,但似乎无法解决数学从例如132天到x天x个月…任何建议?
// GOAL
var timetoGoal = Math.round(goal / costPerDay);
// if more than a year
if ( timetoGoal >= 365 ) {
alert('days + months + years');
// if more than a month but less than a year
} else if ( timetoGoal >= 30 && timetoGoal <=365 ) {
alert('Days + months');
} else {
alert('days');
$('#savings-goal span').text(timetoGoal+' days');
}
解决方法
尝试这样的东西
function humanise (diff) {
// The string we're working with to create the representation
var str = '';
// Map lengths of `diff` to different time periods
var values = [[' year',365],[' month',30],[' day',1]];
// Iterate over the values...
for (var i=0;i<values.length;i++) {
var amount = Math.floor(diff / values[i][1]);
// ... and find the largest time value that fits into the diff
if (amount >= 1) {
// If we match,add to the string ('s' is for pluralization)
str += amount + values[i][0] + (amount > 1 ? 's' : '') + ' ';
// and subtract from the diff
diff -= amount * values[i][1];
}
}
return str;
}
预计这个论点是你想代表的日子差异.它假设一个30天,一年365.
你应该这样使用它
$('#savings-goal span').text(humanise(timetoGoal));
http://jsfiddle.net/0zgr5gfj/