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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8942895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:05:33  来源:igfitidea点击:

Convert a number (of days) to days, months and years with jQuery

javascriptmath

提问by tbwcf

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

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

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?

而不是仅仅显示天数,我想根据数字将其计算为天数和月数或天数、月数和年数。我有一个用于拆分的 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');
}

回答by Matt

Try something like this;

尝试这样的事情;

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;
}

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.

预计参数是您要表示的天数差异。它假设一个月有 30 天,一年有 365 天。

You should be using it like this;

你应该像这样使用它;

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

http://jsfiddle.net/0zgr5gfj/

http://jsfiddle.net/0zgr5gfj/

回答by You Qi

an attempt from me (this take leap year into account and based on the current date)

我的尝试(这考虑了闰年并基于当前日期)

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));

回答by JuanFernandoz

This is a simpler solution that I did without the for bucle:

这是我在没有 for bucle 的情况下所做的更简单的解决方案:

function jarh(x) {
var y = 365;
var y2 = 31;
var remainder = x % y;
var casio = remainder % y2;
year = (x - remainder) / y;
month = (remainder - casio) / y2;

var result ="--- Year ---" + year + "--- Month ---" + month + "--- Day ---" + casio;

return result;
}

var call = jarh(6781);

http://jsfiddle.net/yHAcY/1/

http://jsfiddle.net/yHAcY/1/