javascript – 使用jQuery将数字(天)转换为日,月和年

前端之家收集整理的这篇文章主要介绍了javascript – 使用jQuery将数字(天)转换为日,月和年前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个计算功能,其中的一部分显示了实现目标所需的天数.

而不是仅显示我想要计算的天数和天数几个月或几天,几个月和几年,取决于数量.我有一个if语句的分裂,但似乎无法解决数学从例如132天到x天x个月…任何建议?

  1. // GOAL
  2. var timeToGoal = Math.round(goal / costPerDay);
  3.  
  4. // if more than a year
  5. if ( timeToGoal >= 365 ) {
  6. alert('days + months + years');
  7.  
  8. // if more than a month but less than a year
  9. } else if ( timeToGoal >= 30 && timeToGoal <=365 ) {
  10. alert('Days + months');
  11. } else {
  12. alert('days');
  13. $('#savings-goal span').text(timeToGoal+' days');
  14. }

解决方法

尝试这样的东西
  1. function humanise (diff) {
  2. // The string we're working with to create the representation
  3. var str = '';
  4. // Map lengths of `diff` to different time periods
  5. var values = [[' year',365],[' month',30],[' day',1]];
  6.  
  7. // Iterate over the values...
  8. for (var i=0;i<values.length;i++) {
  9. var amount = Math.floor(diff / values[i][1]);
  10.  
  11. // ... and find the largest time value that fits into the diff
  12. if (amount >= 1) {
  13. // If we match,add to the string ('s' is for pluralization)
  14. str += amount + values[i][0] + (amount > 1 ? 's' : '') + ' ';
  15.  
  16. // and subtract from the diff
  17. diff -= amount * values[i][1];
  18. }
  19. }
  20.  
  21. return str;
  22. }

预计这个论点是你想代表的日子差异.它假设一个30天,一年365.

你应该这样使用它

  1. $('#savings-goal span').text(humanise(timeToGoal));

http://jsfiddle.net/0zgr5gfj/

猜你在找的jQuery相关文章