我在 MySQL 和 PHP 中的日期比较逻辑有问题:日期差异函数对相同日期返回不同的结果。示例:
SQL
SELECT DATEDIFF('2024-06-02', '2024-05-03 12:57')
30
PHP
$x = date_diff( new DateTime( '2024-06-02' ), new DateTime( '2024-05-03 12:57' ) );
当我将使用
where DATEDIFF...
标准从数据库中选择的数据传递给使用 date_diff()
函数检查日期的 PHP 时,这会导致断言错误。
PHP 中的 MySQL 函数是否有严格等效的函数(反之亦然),以便两者都返回 29(或 30)?
两者都应该返回 30,但是您编写的 PHP 代码没有考虑时间,因此它报告 29。
如果您将两者标准化为午夜,它将报告 30 天。
echo $x = date_diff(
(new DateTime( '2024-06-02' ))->setTime(0,0),
(new DateTime( '2024-05-03 12:57' ))->setTime(0,0)
)->days;
// Outputs: 30