PHP如何计算Year中的月份数

时间:2017-12-01 04:56:23

标签: php

  

我想计算特定年份的月数?例如   在1。5年内有多少个月?它很简单,但是我可以如何计算这个?   请有人能告诉我吗??

2 个答案:

答案 0 :(得分:1)

如果您知道年份的数量1.5,则可以通过将其乘以一年中的月数12来计算。

function calcMonths($y){
  return $y * 12;
}

输入:1.5,输出:18。

答案 1 :(得分:0)

如果您有“开始日期”和“结束日期”,则可以轻松计算这两个日期之间的月份,尝试使用“代码”。

$date1 = '2000-01-25';
$date2 = '2010-02-20';

$ts1 = strtotime($date1);
$ts2 = strtotime($date2);

$year1 = date('Y', $ts1);
$year2 = date('Y', $ts2);

$month1 = date('m', $ts1);
$month2 = date('m', $ts2);

echo $diff = (($year2 - $year1) * 12) + ($month2 - $month1);