javascript - Convert a number (of days) to days, months and years with jQuery -
javascript - Convert a number (of days) to days, months and years with jQuery -
i have calculation function , part of shows number of days take accomplish goal.
rather show number of days want calculate days & months or days, months , years depending on number. have if statement splitting can't seem work out maths go illustration 132 days x days x months... suggestions?
// goal var timetogoal = math.round(goal / costperday); // if more year if ( timetogoal >= 365 ) { alert('days + months + years'); // if more month less year } else if ( timetogoal >= 30 && timetogoal <=365 ) { alert('days + months'); } else { alert('days'); $('#savings-goal span').text(timetogoal+' days'); }
try this;
function humanise (diff) { // string we're working create representation var str = ''; // map lengths of `diff` different time periods var values = [[' year', 365], [' month', 30], [' day', 1]]; // iterate on values... (var i=0;i<values.length;i++) { var amount = math.floor(diff / values[i][1]); // ... , find largest time value fits diff if (amount >= 1) { // if match, add together string ('s' pluralization) str += amount + values[i][0] + (amount > 1 ? 's' : '') + ' '; // , subtract diff diff -= amount * values[i][1]; } } homecoming str; }
it's expected argument difference in days want represent. assumes month of 30 days , year of 365.
you should using this;
$('#savings-goal span').text(humanise(timetogoal));
http://jsfiddle.net/0zgr5gfj/
javascript math
Comments
Post a Comment