php datediff获取天数,PHP计算两个日期之间的天数

2629ec01820b11e8d54ca6fc12c22d57.png

实现方式一

$now = time(); // or your date as well

$your_date = strtotime("2010-01-31");

$datediff = $now - $your_date;

echo round($datediff / (60 * 60 * 24));

实现方式二

我阅读了之前所有的解决方案,没有一个使用PHP 5.3工具:DateTime::Diff和DateInterval::Days

日期包含日期到日期之间确切的天数。

使用工具,意味着我们不需要编写代码,因为自己写的代码可能兼容性不是很好,还有可能有潜在的bug。

/**

* We suppose that PHP is configured in UTC

* php.ini configuration:

* [Date]

* ; Defines the default timezone used by the date functions

* ; http://php.net/date.timezone

* date.timezone = UTC

* @link http://php.net/date.timezone

*/

/**

* getDaysBetween2Dates

*

* Return the difference of days between $date1 and $date2 ($date1 - $date2)

* if $absolute parameter is false, the return value is negative if $date2 is after than $date1

*

* @param DateTime $date1

* @param DateTime $date2

* @param Boolean $absolute

* = true

* @return integer

*/

function getDaysBetween2Dates(DateTime $date1, DateTime $date2, $absolute = true)

{

$interval = $date2->diff($date1);

// if we have to take in account the relative position (!$absolute) and the relative position is negative,

// we return negatif value otherwise, we return the absolute value

return (!$absolute and $interval->invert) ? - $interval->days : $interval->days;

}

echo '

2020-03-01 - 2020-02-01: 29 days as it\'s a standard leap year

';

echo getDaysBetween2Dates(new DateTime("2020-03-01"), new DateTime("2020-02-01"), false);

echo '

1900-03-01 - 1900-02-01: 28 days as it\'s a "standard" century

';

echo getDaysBetween2Dates(new DateTime("1900-03-01"), new DateTime("1900-02-01"), false);

echo '

2000-03-01 - 2000-02-01: 29 days as it\'s a century multiple of 400: 2000=400x5

';

echo getDaysBetween2Dates(new DateTime("2000-03-01"), new DateTime("2000-02-01"), false);

echo '

2020-03-01 - 2020-04-01: -28 days as 2020-03-01 is before 2020-04-01

';

echo getDaysBetween2Dates(new DateTime("2020-02-01"), new DateTime("2020-03-01"), false);

share

原创文章,作者:犀牛前端部落,如若转载,请注明出处:https://www.pipipi.net/4563.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值