javascript - 使用 jQuery 将数(天)转换为日、月和年

标签 javascript math

我有一个计算函数,其中一部分显示了实现目标所需的天数。

我不想只显示天数,而是根据天数和月数或天数、月数和年数来计算。我有一个用于拆分的 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/

关于javascript - 使用 jQuery 将数(天)转换为日、月和年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8942895/

相关文章:

algorithm - O(1) 在变化的固定大小数组中的最小值

java - 如何使我的阶乘方法适用于小数? ( Gamma )

javascript - 在 Javascript-IDE spacemacs 中更改默认缩进

javascript - 无对话的 Electron 打印(无声打印)

javascript - 使用存储在数组中的 id 获取元素偏移量

math - SPARQL 中的幂(指数)和其他数学函数支持

math - 使用位移位除以 10?

javascript - 类型错误:无法读取未定义的属性 'number'

javascript - 访问 Handlebar 模板中的 DOM 元素

javaScript - 求给定整数的所有除数之和