【问题标题】:DateTime add 1 day日期时间加 1 天
【发布时间】:2013-07-31 16:03:16
【问题描述】:

我的表单有 2 个字段 - Time_from 和 Time_to

现在我需要每天在我的数据库中添加一个条目(如果这些天之间存在差异) 前任。 Time_from = 2013-08-26 08:00:00 和 Time_to = 2013-08-28 16:00:00 所以在我的数据库中我应该得到 3 个条目

Time_from = 2013-08-26 08:00:00 and Time_to = 2013-08-26 16:00:00
Time_from = 2013-08-27 08:00:00 and Time_to = 2013-08-27 16:00:00
Time_from = 2013-08-28 08:00:00 and Time_to = 2013-08-28 16:00:00

因此,为此我制定了一个方法,我首先找到这两个日期之间的差异,然后我使用一个 for 循环,该循环将在这两个日期的差异中运行尽可能多的天数,最后我只需增加 1 天。

public function createOffer($offer)
{
$time_from = new DateTime($offer->time_from);
$time_to = new DateTime($offer->time_to);
$interval = $time_from->diff($time_to);

for ($counter = 0; $counter <= $interval->d; $counter++) {
    $offer->time_from = $time_from->format('Y-m-d H:i:s');
    $offer_time_to = new DateTime($time_from->format('Y-m-d'));
    $offer_time_to->setTime($time_to->format('H'), $time_to->format('i')
        , $time_to->format('s'));
    $offer->time_to = $offer_time_to->format('Y-m-d H:i:s');

    if ($offer->validate()) {
    $offer->save();
    }

    date_modify($time_from, '+1 day');
    }
}

由于某种原因,代码不起作用。

当我删除 date_modify 字段时,只有第一天会保存在我的数据库中(猜测 for 循环只运行一次)

但是在我的代码中使用 date_modify,数据库中只保存了最后一天。

【问题讨论】:

  • $interval->d 在给定的时间内没有“天”的差异,只有几个小时,因此循环只会运行一次
  • 所以天之间的差异只显示 i 小时?
  • phpfiddle.org/main/code/3r1-6hc 你确定你不想要 $interval->h 而不是 interval->d

标签: php datetime for-loop


【解决方案1】:
$date = new DateTime('2017-01-17');
$date->modify('+1 day');

echo $date->format('Y-m-d'); // 2017-01-18

你也可以这样做:

$dateTo = new \DateTime('1980-12-07 +1 day');
echo $dateTo->format('Y-m-d'); // 1980-12-08

【讨论】:

    【解决方案2】:

    您可以使用Datatime对象的添加功能

    这里我给你一个例子,在你的发布日期中添加一个 1,比如

    <?php
    $date = new DateTime('2000-01-01');
    $date->add(new DateInterval('P1D'));
    echo $date->format('Y-m-d') . "\n";
    ?>
    

    输出

    2000-01-02
    

    希望它能帮助您解决问题。

    【讨论】:

    • 我仍然得到相同的结果,只有最后一天保存在数据库中。
    • 请在传入 new DateTime('your date'); 之前跟踪日期并且您的函数应该在每次新日期时返回,这意味着您需要从函数调用或返回值的 3 次。
    • 您的解决方案似乎有效.. 显然有一个 Jquery 问题,这是造成该错误的原因..
    猜你喜欢
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2018-10-20
    相关资源
    最近更新 更多