PHP Date Intervals using date_add - php

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.

Related

Check with Carbon if a date is on a different day [duplicate]

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

Difference between timestamps in minutes in PHP

I want to get difference between 2 timestamps of format Y-m-d H:i:s in minutes in PHP.
The code used is,
$currentDate = date('Y-m-d H:i:s');
$userLastActivity = date($date);
$timeLapse = (($currentDate - $userLastActivity)/60);
Here, $date is obtained from database.
The value of $timeLapse is 0 in output. Please help.
Try using unix timestamp. Practically it measures the time in seconds from 1/1/1970 and it's a lot easier to use and understand than a php object.
$currentTimestamp = new DateTime()->getTimestamp();
$userLastActivity = date($date)->getTimestamp();
$timeLapse = (($currentDate - $userLastActivity)/60);
You should have the time saved as timestamp on the server too, in that case you could use the $date directly as a number, with no need for a conversion. And also, because it's universal, you can pass it around to javascript or any other language without any worries for conversion
Use strtotime to parse textual datetime into a Unix timestamp and substract $userLastActivity from $currentDate and divide by 60.
See if this helps -
<?php
$currentDate = strtotime(date('Y-m-d H:i:s'));
$date = "2016-10-11 02:40:50";
$userLastActivity = strtotime($date);
echo round(abs($currentDate - $userLastActivity) / 60). " minutes";
?>
For more details :strtotime
Change these 2 lines for a start, as I don't think dividing dates by 60 is gonna work to well.
$currentDate = time();
$userLastActivity = strtotime($date);
That way you have time stamps and not dates (string)

PHP check if two Datetimes are not on the same calendar day

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

PHP: replacement for DateTime object

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);

Calculate two dates with PHP?

I have two dates in the format below:
Start Date = 30-10-2009
End Date = 30-11-2009
How, with PHP could I calculate the seconds between these two dates?
Parse the two dates into Unix timestamps using strtotime, then get the difference:
$firstTime = strtotime("30-10-2009");
$secondTime = strtotime("30-11-2009");
$diff = $secondtime - $firstTime;
The function strtotime() will convert a date to a unix-style timestamp (in seconds). You should then be able to subtract the end date from the start date to get the difference.
$difference_secs = strtotime($end_date) - strtotime($start_date);
I'd rather advice to use built in DateTime object.
$firstTime = new DateTime("30-10-2009");
$diff = $firstTime->diff(new DateTime("30-11-2009"));
As for me it's more flexible and OOP oriented.
In fact previous answer will give you a DateInterval object but not seconds. In order to get seconds with OOP approach you should do this:
$date1 = new DateTime("30-10-2009");
$date2 = new DateTime("30-11-2009");
$seconds = $date2->getTimestamp() - $date1->getTimestamp();

Categories