获取两个日期之间月份数的优雅方法? [英] Elegant way to get the count of months between two dates?

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

问题描述

假设我在变量中有两个日期,例如

Let's assume I have two dates in variables, like

$date1 = "2009-09-01";
$date2 = "2010-05-01";

我需要获取$date2$date1($date2 >= $date1) 之间的月数.IE.我需要获得 8.

I need to get the count of months between $date2 and $date1($date2 >= $date1). I.e. i need to get 8.

有没有办法通过使用 date 函数来获取它,或者我必须分解我的字符串并进行所需的计算?

Is there a way to get it by using date function, or I have to explode my strings and do required calculations?

谢谢.

推荐答案

对于 PHP >= 5.3

For PHP >= 5.3

$d1 = new DateTime("2009-09-01");
$d2 = new DateTime("2010-05-01");

var_dump($d1->diff($d2)->m); // int(4)
var_dump($d1->diff($d2)->m + ($d1->diff($d2)->y*12)); // int(8)

DateTime::diff 返回一个 DateInterval 对象

DateTime::diff returns a DateInterval object

如果您不使用 PHP 5.3 或更高版本,我想您将不得不使用 unix 时间戳:

If you don't run with PHP 5.3 or higher, I guess you'll have to use unix timestamps :

$d1 = "2009-09-01";
$d2 = "2010-05-01";

echo (int)abs((strtotime($d1) - strtotime($d2))/(60*60*24*30)); // 8

但这不是很精确(每个月并不总是 30 天).

But it's not very precise (there isn't always 30 days per month).

最后一件事:如果这些日期来自您的数据库,那么使用您的 DBMS 来完成这项工作,而不是 PHP.

Last thing : if those dates come from your database, then use your DBMS to do this job, not PHP.

如果您不能使用 DateTime::diff 或您的 RDBMS,此代码应该更精确:

This code should be more precise if you can't use DateTime::diff or your RDBMS :

$d1 = strtotime("2009-09-01");
$d2 = strtotime("2010-05-01");
$min_date = min($d1, $d2);
$max_date = max($d1, $d2);
$i = 0;

while (($min_date = strtotime("+1 MONTH", $min_date)) <= $max_date) {
    $i++;
}
echo $i; // 8

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

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