用PHP计算两个日期之间的月数? [英] Calculate the number of months between two dates in PHP?

查看:468
本文介绍了用PHP计算两个日期之间的月数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不使用PHP 5.3的 date_diff 功能(我是使用PHP 5.2.17),是否有一个简单而准确的方法呢?我正在考虑下面的代码,但我不知道如何解释闰年:

Without using PHP 5.3's date_diff function (I'm using PHP 5.2.17), is there a simple and accurate way to do this? I am thinking of something like the code below, but I don't know how to account for leap years:

$days = ceil(abs( strtotime('2000-01-25') - strtotime('2010-02-20') ) / 86400);
$months = ???;

我正在努力计算一个人的几个月。

I'm trying to work out the number of months old a person is.

推荐答案

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

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

您可能希望将日期包含在某个地方,具体取决于您是否意味着 em>几个月或几个月。希望你得到想法。

You may want to include the days somewhere too, depending on whether you mean whole months or not. Hope you get the idea though.

这篇关于用PHP计算两个日期之间的月数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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