我有一个计算功能,其中一部分显示了实现目标所需的天数.
而不是仅仅根据数量显示我想要计算天数和月数,天数,月数和年数的天数.我有一个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');
}
Run Code Online (Sandbox Code Playgroud)
Mat*_*att 11
尝试这样的事情;
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;
}
Run Code Online (Sandbox Code Playgroud)
预计参数是您想要表示的天数差异.假设一个月为30天,一年为365.
你应该像这样使用它;
$('#savings-goal span').text(humanise(timeToGoal));
Run Code Online (Sandbox Code Playgroud)
来自我的尝试(根据当前日期考虑闰年)
function humanise(total_days)
{
//var total_days = 1001;
var date_current = new Date();
var utime_target = date_current.getTime() + total_days*86400*1000;
var date_target = new Date(utime_target);
var diff_year = parseInt(date_target.getUTCFullYear() - date_current.getUTCFullYear());
var diff_month = parseInt(date_target.getUTCMonth() - date_current.getUTCMonth());
var diff_day = parseInt(date_target.getUTCDate() - date_current.getUTCDate());
var days_in_month = [31, (date_target.getUTCFullYear()%4?29:28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var date_string = "";
while(true)
{
date_string = "";
date_string += (diff_year>0?diff_year + "Y":"");
if(diff_month<0){diff_year -= 1; diff_month += 12; continue;}
date_string += (diff_month>0?diff_month + "M":"");
if(diff_day<0){diff_month -= 1; diff_day += days_in_month[((11+date_target.getUTCMonth())%12)]; continue;}
date_string += (diff_day>0?diff_day + "D":"");
break;
}
console.log(date_string);
return date_string;
}
var timeToGoal = 1001;
$('#savings-goal span').text(humanise(timeToGoal));
Run Code Online (Sandbox Code Playgroud)