首页 > 解决方案 > DateTime::diff 的意外结果

问题描述

我有两个约会。系统中的当前日期和另一个日期,该日期前后 +/- 几天。我想知道这两个日期之间的区别,并通过以下方式进行了尝试:

// today is 02/19/2021 ("19.02.2021")
// 1. try: $dstring = "18.02.2021"; result: 1, expected
// 2. try: $dstring = "19.02.2021"; result: 0, expected
// 3. try: $dstring = "20.02.2021"; result: 0, not expected
// 4. try: $dstring = "21.02.2021"; result: 1, not expected
function daysDiff(string $dstring) {
    $now = new DateTime();
    return $now->diff(new DateTime($dstring))->d;
}

当今天 $dstring <= 时,该函数工作正常。但是当 $dstring > today 时,结果太少了 1 天。

任何想法为什么会这样?

标签: php

解决方案


它可以正常工作'today'

// today is 02/19/2021 ("19.02.2021")
// 1. try: $dstring = "18.02.2021"; result: 1
// 2. try: $dstring = "19.02.2021"; result: 0
// 3. try: $dstring = "20.02.2021"; result: 1
// 4. try: $dstring = "21.02.2021"; result: 2
function daysDiff(string $dstring) {
    // $now = new DateTime();
    $now = new DateTime('today');
    return $now->diff(new DateTime($dstring))->d;
}

推荐阅读