Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime add 1 day

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.

like image 629
CreamYGEEK Avatar asked Jul 31 '13 08:07

CreamYGEEK


People also ask

How do you increase days in Python?

Add Days to datetime Object If we want to add days to a datetime object, we can use the timedelta() function of the datetime module. The previous Python syntax has created a new data object containing the datetime 2024-11-24 14:36:56, i.e. 18 days later than our input date.

How do I add time to a datetime?

Use the timedelta() class from the datetime module to add time to datetime, e.g. result = dt + timedelta(hours=2, minutes=25, seconds=24) . The timedelta class can be passed the hours , minutes and seconds arguments and adds the specified time to the datetime. Copied!

How do you go back a day in Python?

You can subtract a day from a python date using the timedelta object. You need to create a timedelta object with the amount of time you want to subtract. Then subtract it from the date.


1 Answers

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.

like image 156
liyakat Avatar answered Oct 26 '22 14:10

liyakat