DateTime add 1 day

datetime, for-loop, php

Solution

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.

Problem

My Form has 2 fields - Time_from and Time_to 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 ``` 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. 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) But with the date_modify in my code, only the last day is saved in the database.

Original source