DateTime添加1天

编程入门 行业动态 更新时间:2024-10-24 05:23:21
本文介绍了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天

本文发布于:2023-11-09 22:59:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573669.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:DateTime

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!