The server that I have my sited hosted is on PHP5.12.14, and I have an error when I run the DateTime object from PHP5.3
# DateTime::add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
$date = new DateTime($item_user['mem_updated']);
# add a day to the object
$date -> add(new DateInterval('P1D'));
the error,
Fatal error: Call to undefined method DateTime::add() in /homepages/xxx.php on line xx
So, I have look for the other solutions rather than sticking to PHP5.3's DateTime object. How can I write the code to replace the code above?
basically I have this date and time data (for instance - 2011-01-21 02:08:39) from the mysql database, and I just need to add 1 day or 24 hours to that date/time, then passing it into a function below,
$time_togo = time_togo($date -> format('Y-m-d H:i:s'));
thanks.
strtotime would work
$timestamp = strtotime($item_user['mem_updated']);
$time_togo = date("Y-m=d H:i:s", strtotime("+1 Day", $timestamp));
Here's an example:
$date = date('Y-m-d H:i:s');
$new_tstamp = strtotime($date.'+1WEEK');
$new_date = date('Y-m-d H:i:s', $new_tstamp);
In other words, strtotime lets you use date expressions like +1DAY, +1MONTH and so on.
The above will work for date string (e.g.: 2010-01-01). If your original date is a Unix timestamp, you can still use strtotime, although a bit differently:
$new_tstamp = strtotime('+1WEEK', $timestamp);
Related
The below code doesn't subtract 1 year from the date. Why?
$date1 = '2021-06-02';
$date2 = new \DateTime(date($date1, strtotime('-1 year')));
echo $date2->format('Y-m-d'); // outputs the same date 2021-06-02
Part of your problem is that the date function's first argument is the format of the date.
https://www.php.net/manual/en/function.date.php
So what is happening is that you are creating a date string with the format of '2021-06-02'.
https://www.php.net/manual/en/datetime.format.php
This doesn't use anything from the timestamp that you are providing so this string is passed to the constructor of DateTime and creating the date instead of the one from the year previous.
Please use this code. Its always works for me.
$date1 = '2021-06-02';
$date2 = date("Y-m-d", strtotime("-1 year", strtotime($date1)));
echo $date2; //Output 2020-06-02
This is for Date time object:
$dt = new DateTime('2021-06-02');
$minusOneYearDT = $dt->sub(new DateInterval('P1Y'));
$minusOneYear = $minusOneYearDT->format('Y-m-d');
echo $minusOneYear;
OR make a small solution:
$time = new DateTime('2021-06-02');
$newtime = $time->modify('-1 year')->format('Y-m-d');
echo $newtime;
Your code is a bit of a muddle:
date() takes as parameters a format string, and an integer representing a point in time; it then applies the format to create a string for that date and time
strtotime() takes a string, interprets it as a point in time, and returns an integer timestamp
new DateTime() takes a string, in any of the formats strtotime would accept, but creates an object representation rather than returning an integer
You've tried to use all of them at once, and got in a mess:
Your call to date() has a first parameter of '2021-06-02', which isn't a valid format.
Your call to strtotime() has a parameter of '-1 year', which will just be interpreted as "1 year before now", not relative to anything else you've specified.
Using both of those functions and then passing to new \DateTime() doesn't make a lot of sense, since the object can do all the same things those functions can do.
If you want to use the integer-based functions, you could write this:
$date1 = '2021-06-02';
$date2 = strtotime("$date1 -1 year");
echo date('Y-m-d', $date2);
If you want to use the object-based functions, you could write this:
$date1 = '2021-06-02';
$date2 = new \DateTime("$date1 -1 year");
echo $date2->format('Y-m-d');
Or this (note the use of DateTimeImmutable instead of DateTime to avoid the modify method changing the $date1 object:
$date1 = new \DateTimeImmutable('2021-06-02');
$date2 = $date1->modify('-1 year');
echo $date2->format('Y-m-d');
just trying to create a variable where it outputs the exact current datetime and adding exactly one additional year. how do i add the days?
$expirationdate = date('Y-m-d H:i:s', .' + 1 year'));
Lets say the exact current date is 2019-01-23 17:11:25
the variable will be: 2020-01-23 17-11-25 (+365)
Also, if a person manually modifies the date on their PC/Phone, will that time be the start of the current date on the variable?
You can achieve your result by using strtotime() and date() function of php
$expirationdate = date('Y-m-d H:i:s', strtotime('+ 1 year'));
print_r($expirationdate);
You can read more about the strtotime() and date()
Try with below code:
$expirationdate = date('Y-m-d H:i:s', strtotime('+1 years'));
I hope it will help you.
Try This :
$date= date('Y-m-d H:i:s',strtotime('+1 years'));
I think the best way to work with dates and time in PHP is through the DateTime object. You can use modify method to add or subtract days, years or whatever you want, like this:
$d = new DateTime(); //current date
$d->modify('+10 days');
$d->modify('+1 year');
echo $d->format('Y-m-d H:i:s');
Regarding your second question if a person modifies date on his computer it won't change anything because PHP runs on the server and takes date from it (not from the user machine).
I have two Datetimes like this (the dates being actually $vars)
$startTime = \DateTime::createFromFormat('Y/m/d H:i', '2015/01/01 23:00');
$endTime = \DateTime::createFromFormat('Y/m/d H:i', '2015/01/02 01:00');
I struggle with a (possibly pretty) simple problem: How could I determine if the two dates are on different calendar days?
I cannot do < as 2015/01/01 22:00 < 2015/01/01 23:00 would also be true. I can also not do this:
$diff = $startTime->diff($endTime);
$days = $diff->format('%d');
echo $days;
as it gives me 0.
THIS gives me an idea about how to do it, but for javascript, what would be the equivalent for php?
//UPDATE
$startDate = $startTime->format('Y/m/d');
$endDate = $endTime->format('Y/m/d');
$diffDates = $startDate->diff($endDate);
$daysDiff = $diffDates->format('%d');
echo $daysDiff;
I think that might be the right approach now, thanks to the comments, but now I get Error: Call to a member function diff() on string
//UPDATE FOR CLARIFICATION WHAT I'M TRYING TO DO
I just want to have the difference in days, so for the above it would be '1' (although only 2 hours difference actually) and for example '2015/01/01 23:00' and '2015/01/03 17:00' would be '2'.
Just create the dates with time set to 00:00:00:
$startTime = \DateTime::createFromFormat('Y/m/d H:i:s', '2015/01/01 00:00:00');
$endTime = \DateTime::createFromFormat('Y/m/d H:i:s', '2015/01/02 00:00:00');
or reset time to zero on existing dates:
$startTime->setTime(0, 0, 0);
$endTime->setTime(0, 0, 0);
then it should work:
$diff = $startTime->diff($endTime);
$days = $diff->format('%d');
echo $days; // 1
Bonus
If you want to work only with dates, remember to set the time to 00:00:00 in createFromFormat or reset it with setTime. If you won't provide time in createFromFormat PHP will set it to the current time:
$date = DateTime::createFromFormat('Y-m-d', '2016-01-21');
print $date->format('H:i:s'); //not 00:00:00
To fix it, you must either:
provide 00:00:00 time in format:
$date = DateTime::createFromFormat('Y-m-d H:i:s', '2016-01-21 00:00:00');
prefix the date format with exclamation mark and omit the time, this will set the time to 00:00:00 automatically:
$date = DateTime::createFromFormat('!Y-m-d', '2016-01-21');
reset the time after creation:
$date = DateTime::createFromFormat('Y-m-d', '2016-01-21');
$date->setTime(0, 0);
I think this is one of the few situations where the use of strings for date calculations is justified:
function onDifferentDays(\DateTimeInterface $startTime, \DateTimeInterface $endTime){
return $startTime->format('Y-m-d')!==$endTime->format('Y-m-d');
}
This code should be easy to extend to include time zone.
There're other alternatives but I don't think they're normally worth the effort:
Compare element by element (day, month and year):
The PHP DateTime class doesn't offer dedicated functions, only format().
Normalize both dates to a common time and compare with == (not ===):
Unless you're using immutable objects you need to clone input or expect side effects
You also need to ensure that time exists in the active time zone though midnight is probably safe enough.
Whatever, YMMV ;-)
Comparing formatted dates is the right thing to do:
$a->format('Y-m-d') === $b->format('Y-m-d')
There is a method for that if you use Carbon:
$dt1->isSameDay($dt2)
So I recommend to use it instead of previous answers given here.
http://carbondoc/docs/#api-comparison
I'm trying to calculate the difference between 2 dates: $now and $old to get -> how long as past since old datetime.
$current_date = time();
$old= new DateTime($dateTimeString);
$now= new DateTime($current_date);
$interval = $now->diff($old);
I was trying with these values: 2016-02-23 02:15:43 --- 2016-02-22 21:45:11 and the result was more than 14hours of difference. I print the result like this:
$interval->format('%i Hours ago.');
$interval->format('%d Days ago.');
What I am doing wrong please?
The problem is here:
$current_date = time();
$now = new DateTime($current_date);
The value returned by time() is the number of seconds since 1970-01-01 00:00:00 UTC. The DateTime constructor tries to interpret it as a date that uses one of the usual date formats, it fails and produces a DateTime objects initialized with 0 (i.e. 1970-01-01 00:00:00 UTC).
If you want to create a new DateTime object from an Unix timestamp (the value returned by time() you can use DateTime::createFromFormat()
$current_time = time();
$now = DateTime::createFromFormat('U', $current_time);
Or you can pass the timestamp prefixed with '#' to DateTime::__construct():
$current_time = time();
$now = new DateTime('#'.$current_time);
This format is explained in the Compound date/time formats page.
But the easiest way to create a DateTime object that contains the current date and time is to either pass 'now' as argument to the constructor or omit it altogether:
$now1 = new DateTime('now');
$now2 = new DateTime();
The two DateTime objects constructed above should be identical (there is a small chance they are 1-second apart, though) and they both must contain the current date & time.
I have the following code which works on the first 2 lines, taking my start date, converting to unix timestamp, and then adding one day.
The 3rd line is trying to use the value that is then generated to use the date interval to find the date in 2 months.
Unfortunately, the date_add seems to return the error 'date_add() expects parameter 1 to be DateTime, integer given'.
Can anyone tell me how I accomplish this using unix timestamp?
$startdate = strtotime('2014/12/19 15:00');
$weekstart = $startdate - (date("N",$startdate)*60*60*24)+(60*60*24);
$enddate = date_add($weekstart, DateInterval::createfromDateString('2 months'));
Seems that you are wanting to create two different DateTime strings with different intervals. This should do it.
$startdate = new DateTime('2014/12/19 15:00');
$weekstart = $startdate->modify('+1 day');
$weekstart = $weekstart->format('U'); //change $weekstart to unix timestamp//
$enddate = $startdate->modify('+2 months');
$enddate = $enddate->format('U'); //change $enddate to unix timestamp//
So use a DateTime:
$startdate = new DateTime('2014/12/19 15:00');
internally DateTime's constructor will be using strtotime() anyways, giving you all the benefits (and risk) of strtotime()'s parsing logic, plus all the benefits of having the entire DateTime object available from the get-go.
The rest of your datemath can be accomplished using pure DateTime operations as well,w ithout having to do manual 60*60*24-type stuff.