Add days to DateTime in PHP -- without modifying original - php

How can I add a number of days to a DateTime object without modifying the original. Every question on StackOverflow appears to be about date and not DateTime, and the ones that do mention DateTime talk about modifying the original.
Eg.
$date = new DateTime('2014-12-31');
$date->modify('+1 day');
But how can you calculate a date several days in advance without modifying the original, so you can write something like:
if($dateTimeNow > ($startDate + $daysOpen days) {
//
}
I could always just create another DateTime object, but I'd rather do it the above way.

Use DateTimeImmutable, it's the same as DateTime except it never modifies itself but returns a new object instead.
http://php.net/manual/en/class.datetimeimmutable.php

you can take the original variable in a separate variable and add no. of days in other variable so you have both(original and updated)value in different variable.
$startDate = new DateTime('2014-12-31');
$endDate = clone $startDate;
$endDate->modify('+'.$days.'days');
echo $endDate->format('Y-m-d H:i:s');
You can always use clone, too:
$datetime = clone $datetime_original;

Related

How can I add current time to an existing date object?

I have a date object like so:
2016-06-30 00:00:00
What I need is take the current time, let's say
01.07.2016 14:56
Add to the first date object so it would look like this:
2016-06-30 14:56:00
I understand that one can add time by adding to a strtotime object and one can also use the add function of datetime. But what I have a hard time is figuring out how to extract the time part and then add it to the first datetime object.
Is there a simple way for it or am I going to have to kind of hack it?
Thank you
This explains how you can do it: Set Time
Just call:
date_time_set($date, 14, 56, 00); // $date is your date object
Since the date object is always midnight the value of the time is zero and can therefor be overwritten without loosing any information. If you can have more then 24 Hours to add there are other better ways. But for this we would need more information.
<?php
$d1 = '01.07.2016 14:56';
$dt = new DateTime($d1);
$date = $dt->format('m/d/Y');
$time = $dt->format('H:i:s');
$d2 ='2016-06-30 00:00:00';
$dt2 = new DateTime($d2);
$date2 = $dt2->format('Y-m-d');
$final_date=$date2.' '.$time;
echo $final_date ;
Result== 2016-06-30 14:56:00
$_SERVER['REQUEST_TIME'], if you don't want to create a new object
get the "datediff()" and then use modify to add that to existing object.
When you change the time at almost midnight and potentially you should change the date also. In this scenario if you use "modify()" and add TimeInterval to it. system will take care of the Date change also.
if you are not worried about date changes. then setTime() is always there for us.

DateTime Class. shorter way to set date to start of the day (or without time altogether)

Currently when I want to get today's date irrespective of time, I have to do the following.
$Date = new DateTime('now');
$Date->setTime(0,0,0);
Is there a more eloquent way of doing this? Preferably a one-liner
Assuming you are using PHP 5.4+
$Date = (new DateTime('now'))->setTime(0,0,0);
Or
$Date = new DateTime('midnight');

Calculating the date weeks using the date() function

I have a website which saves images into a database. I have successfully made a function that calculates the date that an image is added and this value is also saved into the database. I now want to calculate the date two weeks ahead from the addition date. This will show the date that the image file will cease to exist in the database.
I used the function:
$dateofaddedimage= date("d/m/Y");
This calculate thee current date of the addition of the image.
I am aware that there is the strtodate() function, but i don't think it will help.
Does anyone know how to add two weeks onto this function?
Thanks!
Add a number to time(), which is the current time stamp as seconds from the Unix Epoch.
$twoweeks = time() + (2*7*24*60*60);
$thatasdate = date("d/m/Y", $twoweeks) ;
Check out date_add and the PHP DateTime model.
From the php manual page comes this fine example:
<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P10D'));
echo $date->format('Y-m-d') . "\n";
If you use this on your problem, you'd have
<?php
$dateofaddedimage = new DateTime('now'); //creates DateTime Model of today (and now)
$dateofimagedestroy = new DateTime('now'); //creates DateTime Model of today as well
$dateofimagedestroy->add(new DateInterval('P14D')); // adds 14 Days to the second date
The problem with what you are doing is that date() returns a string formatted to the date - not a proper date.
I would suggest either inserting a datetime into the database such as:
insert into yourTable (timeColumn) values (now());
This will insert the actual date. From there you can use mysql functions to add and subtract from this date.
Or using a timestamp in your code such as:
$uploadedTime=time();
From there you can either use PHP functions to add or subtract dates, or (as it is a timestamp) you can also use mysql functions to calculate what you need inside queries themselves.

Modify an existing DateTime object using a string containing a timestamp in PHP

I've got a variable declared like such: $var = new DateTime(null);.
I want to change the time that echo $var->format('g:i A'); outputs.
I want to achieve this solely by using a time string such as 07:30:28.
How can I do this without re-creating a DateTime object ($var) each time? I can't think of a way to achieve this.
DateTime::modify() will do exactly what you want. It will quite happily accept a time in string format and apply it to the object:-
$date = new \DateTime();
$date->modify('07:30:28');
See it working.
Alternatively, you can do it all in one go:-
$date = (new \DateTime())->modify('07:30:28');

PHP DateTime for .NET developers

PHP's DateTime class has the two methods add() and sub() to add or subtract a time span from a DateTime object. This looks very familiar to me, in .NET I can do the same thing. But once I tried it, it did very strange things. I found out that in PHP, those methods will modify the object itself. This is not documented and the return value type indicates otherwise. Okay, so in some scenarios I need three lines of code instead of one, plus an additional local variable. But then PHP5's copy by reference model comes into play, too. Just copying the object isn't enough, you need to explicitly clone it to not accidently modify the original instance still. So here's the C# code:
DateTime today = DateTime.Today;
...
if (date < today.Add(TimeSpan.FromDays(7)) ...
Here's the PHP equivalent:
$today = new DateTime('today');
...
$then = clone $today;
$then->add(new DateInterval('P7D'));
if ($date < $then) ...
(I keep a copy of today to have the same time for all calculations during the method runtime. I've seen it often enough that seconds or larger time units change in that time...)
Is this it in PHP? I need to write a wrapper class for that if there's no better solution! Or I'll just stay with the good ol' time() function and just use DateTime for easier parsing of the ISO date I get from the database.
$today = time() % 86400;
...
if ($date < $today + 7 * 86400) ...
Time zones not regarded in these examples.
Update: I just found out that I can use the strtotime() function as well for parsing such dates. So what's the use for a DateTime class in PHP after all if it's so complicated to use?
Update^2: I noticed that my $today = ... thing above is garbage. Well, please just imagine some correct way of getting 'today' there instead...
It looks like you will definitely have to make a clone of the object. There does not seem to be a way to create a copy of the DateTime object any other way.
As far as I can see, you could save one line:
$today = new DateTime('today');
...
$then = clone $today;
if ($then->add(new DateInterval('P7D')) < $then) ...
I agree this isn't perfect. But do stick with DateTime nevertheless - write a helper class if need be. It is way superior to the old date functions: It doesn't have the year 2038 bug, and it makes dealing with time zones much, much easiert.

Categories