19

我已经开始在我的应用程序中使用 PHP Carbon,因为它似乎比使用和操作 DateTime 类的日期/时间要容易得多。我想要做的是检查选择的日期($chosen_date)是否大于另一个日期($whitelist_date)。我在下面的代码中试过这个:

    $chosen_date = new Carbon($chosen_date);

    $whitelist_date = Carbon::now('Europe/London');
    $whitelist_date->addMinutes(10);

    echo "Chosen date must be after this date: ".$whitelist_date ."</br>";
    echo "Chosen Date: ".$chosen_date ."</br>";

    if ($chosen_date->gt($whitelist_date)) {

        echo "proceed"; 
    } else {
        echo "dont proceed";
    }

原始 $chosen_date 值来自 POST 数据。这是我得到的输出:

Chosen date must be after this date: 2015-09-22 21:21:57
Chosen Date: 2015-09-22 21:01:00
proceed

显然,所选日期不大于白名单日期,但 if 语句仍然返回 true 并回显“继续”。我一遍又一遍地检查代码,但我看不出哪里出错了。

4

2 回答 2

18

可能是,时区不一样,所以试试这个

$chosen_date = new Carbon($chosen_date, 'Europe/London');

$whitelist_date = Carbon::now('Europe/London');
$whitelist_date->addMinutes(10);

请记住,您始终可以构建实例并为其设置时区:

$date = new Carbon();
$date->setTimezone('Europe/London');

$whitelist_date = $date->now();

关于如何为不同时区的用户管理数据的任何提示?

您可以创建具有不同时区的不同对象。试试这个并玩弄结果。

$london_date = new Carbon($chosen_date_from_london, 'Europe/London');
$colombia_date = new Carbon($chosen_date_from_colombia, 'Bogota/America');

假设您比较它们:

$are_different = $london_date->gt($colombia_date);
var_dump($are_different); //FALSE

不,它们并没有什么不同,尽管它们是不同的时间,当你盯着时钟时,在世界的不同地方,它们仍然处于同一个现在时刻,即现在。

你去吧,只需创建不同的对象或 Carbon() 实例,并使用设置不同的时区$instance->setTimeZone(TimeZone);

于 2015-09-22T20:39:40.420 回答
-2

或尝试使用以下一个:

if ($chosen_date->gte($whitelist_date))
于 2015-09-22T20:25:32.103 回答