DateTime添加1天 [英] DateTime add 1 day

查看:744
本文介绍了DateTime添加1天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My Form has 2 fields - Time_from and Time_to

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

Now i need to add an entry in my database for each day (If theres is a difference between those days) ex. Time_from = 2013-08-26 08:00:00 and Time_to = 2013-08-28 16:00:00 So in my database i should get 3 entries

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天。

So for that purpose i have made a method, where i first find the difference between those 2 dates and then i'm using a for loop that will run as many days in difference those 2 dates have, and at the end im just adding 1 day.

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');
    }
}

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

For some reason, the code doesn't work.

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

When i remove the date_modify field only the first day will be saved in my database (Guess the for loop is only running once then)

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

But with the date_modify in my code, only the last day is saved in the database.

推荐答案

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

you can use Add function of Datatime object

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

here i am giving you one example to add one 1 in your post date like

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

OUTPUT

2000-01-02

希望它能帮助你解决你的问题。

Hope it will sure help you to solve your issue.

这篇关于DateTime添加1天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆