我想根据两个日期计算天数,但给出的天数不正确。
我有2个变量
$date=$date[1];
来自数据库
$now =date('d/m/Y')
;当前日期
$date
变量值为(来自数据库)05/03/2019
我使用以下脚本根据两个日期计算天数,但返回 120 天。
方法1
$date=$date[1]; `Is coming from Database`
$now =date('d/m/Y');
$date1 = new DateTime($now);
$date2 = new DateTime($date);
$diff = $date2->diff($date1)->format("%a");
方法2
$datetime1 = new DateTime($now);
$datetime2 = new DateTime($date);
$difference = $datetime1->diff($datetime2);
echo 'Difference: '.$difference->y.' years, '
.$difference->m.' months, '
.$difference->d.' days';
print_r($difference);
但它在以下输出中返回错误的日期
Difference: 0 years, 4 months, 120 daysDateInterval Object
(
[y] = 0
[m] = 4
[d] = 0
[h] = 0
[i] = 0
[s] = 0
[invert] = 0
[days] = 120
)
为什么给出了错误的天数输出?
最佳答案
如果您使用“d/m/Y”格式,则应使用createFromFormat
函数将字符串日期转换为日期对象。例如:
$date1 = new \DateTime();
$date2 = \DateTime::createFromFormat('d/m/Y', '05/03/2019');
$diff = $date2->diff($date1)->format("%a");
关于php - 天数计算未给出正确的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54945057/