我有一个计算函数,其中一部分显示了实现目标所需的天数。
我不想只显示天数,而是根据天数和月数或天数、月数和年数来计算。我有一个用于拆分的 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));
关于javascript - 使用 jQuery 将数(天)转换为日、月和年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8942895/