使用jQuery将数字(天)转换为天,月和年 [英] Convert a number (of days) to days, months and years with jQuery

查看:1044
本文介绍了使用jQuery将数字(天)转换为天,月和年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a calculation function and part of this shows the number of days it will take to achieve a goal.

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

Rather than just show the number of days I want to calculate this into days & months or days, months and years depending on the number. I have an if statement for the splitting but can't seem to work out the maths to go from for example 132 days to x days x months... Any suggestions?

// 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.

It's expected that the argument is the difference in days you want to represent. It assumes a month of 30 days and a year of 365.

您应该像这样使用它;

You should be using it like this;

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

http://jsfiddle.net/0zgr5gfj/

这篇关于使用jQuery将数字(天)转换为天,月和年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆