将月数转换为年数和月数

时间:2015-10-27 19:39:37

标签: php

我使用for循环显示数字1-60:

for($i=0; $i<=60; $i++)
循环中,我希望能够显示年数和月数。例如:

1 month
2 months
3 month
...
1 year
1 year 1 month
1 year 2 month

依旧......

我试过这个:

if(!is_float($i/12)) {
    $years = $i/12;
} else {
    $years = 'no';
}

这显示12个月1个,24个月2个,但不是

之间

4 个答案:

答案 0 :(得分:2)

您可以将%/用于整数部分和其余部分 试试这个循环来显示结果

 for($i=1; $i<=60; $i++){

        echo 'year = ' . floor($i/12) . ' month = ' .$i%12 . '<br />';

 }

答案 1 :(得分:0)

我使用以下解决方案在@scaisEdge

的帮助下完成我的代码
for($i=0; $i<=60; $i++) {
    if(!is_float($i/12)) {
        $years = floor($i / 12).' Year';
        $years = $years.($years > 1 ? 's' : '');
        if($years == 0) {
            $years = '';
        }
    }
    $months = ' '.($i % 12).' Month';
    if($months == 0 or $months > 1) {
        $months = $months.'s';
    }

    $display = $years.''.$months;
    echo '<option value="'.$i.'"';
    if($result["warrenty"] == $i) {
        echo 'selected="selected"';
    }
    echo '>'.$display.'</option>';
}

答案 2 :(得分:0)

function yearfm($months)
{
  $str = '';

  if(($y = round(bcdiv($months, 12))))
  {
    $str .= "$y Year".($y-1 ? 's' : null);
  }
  if(($m = round($months % 12)))
  {
    $str .= ($y ? ' ' : null)."$m Month".($m-1 ? 's' : null);
  }
  return empty($str) ? false : $str;
}
for($x = 0; $x < 100; $x++)
{
  var_dump(yearfm($x));
}

答案 3 :(得分:0)

另一种解决方案1:

for ($i=0; $i<=60; $i++) {
    $output = [];
    if ($i >= 12) {
        $years    = ($i - $i % 12) / 12;
        $output[] = $years > 1 ? $years . ' years' : $years . ' year';
    }

    if ($i % 12 > 0) {
        $monthsRest = $i % 12;
        $output[]   = $monthsRest > 1 ? $monthsRest . ' months' : $monthsRest . ' month';
    }
    echo implode(' ', $output);
}

另一个解决方案2:

for ($i=0; $i<=60; $i++) {
    $output    = [];
    $startDate = new DateTime();
    $endDate   = new DateTime('+' . $i . ' months');

    $interval  = $startDate->diff($endDate);
    $years     = $interval->format('%y');
    $months    = $interval->format('%m');

    if ($years > 0) {
        $output[] = $years > 1 ? $years . ' years' : $years . ' year';
    }

    if ($months > 0) {
        $output[] = $months > 1 ? $months . ' months' : $months . ' month';
    }

    echo implode(' ', $output);
}
相关问题