DateTime Comparison with objects php - php

This may be the most simple question however i don't know to best aproach this
I have 2 dates to compare $lp & now()
$lp = $ur->getLastPost($usr) ?: new \DateTime('yesterday');
$tdiff = date_diff(strtotime($lp),strtotime('now'));
$lp can either be 2019-11-21 17:20:44 or an current yesterday time
I want to transform $lp in a unixtimestamp so I can see if the difference is bigger than 3600 seconds
My problem is that i can't use strtotime because $lp can be an object, hence the error strtotime() expects parameter 1 to be string, object given

You must parse datetime to format of you $lp:
$date = new DateTime($ur->getLastPost($usr) ?: 'yesterday');
$date->format('Y-m-d H:i:s');
then you can use date_diff to get difference of dates.
print_r($date->diff(new \DateTime('now')));
see DateTime::diff and Datetime class

Related

Not getting the required date

I want to calculate the difference between date using date_diff(), whose 1st parameter is saved data in database and the 2nd parameter is today's date. The $pro_deadline is coming from database and is of type text (format yyyy-mm-dd), so I converted it into time using strtotime(). But in the end I'm getting "
Warning
: date_diff() expects parameter 1 to be DateTimeInterface, string given"
$today = date("Y-m-d");
echo $today;
$end = strtotime($pro_deadline);
$end_line = date("Y-m-d",$end);
echo $end_line;
$diff = date_diff($end_line,$today);
echo $diff;
as per PHP documentation http://php.net/manual/en/function.date-diff.php
date_diff — Alias of DateTime::diff()
so the perameters to date_diff should be DateTimeInterface types.
i would try
<?php
$today = date("Y-m-d");
echo $today." ";
$today = date_create($today);
$pro_deadline = '10-15-18';
$end = strtotime($pro_deadline);
$end_line = date_create(date("Y-m-d",$end));
$diff = date_diff($end_line,$today);
echo $diff->format('%a');
echo " days apart";
?>
the date_create() function is an alias of the DateTime constructor.
http://php.net/manual/en/datetime.construct.php
this creates an interface for the date/time that the date_diff() function can interpret. then date_diff() returns a DateInterval object
http://php.net/manual/en/class.dateinterval.php
the DateInterval object has a format method
http://php.net/manual/en/dateinterval.format.php
that can return the date in a sting for you.
Hope this explanation helps!
Like the error message says, date_diff expects DateTimeInterface parameters. strtotime returns a timestamp as an integer, which it can't work with.
Instead of creating timestamps, you can pass your deadline to the DateTime constructor, along with another version that'll default to now:
$today = new DateTime;
$end = new DateTime($pro_deadline);
and then pass these two objects to date_diff, and use the DateInterval::format method to display the number of days (assuming this is your desired output):
$diff = date_diff($today,$end);
echo $diff->format('%a');
See https://3v4l.org/QVkad for a full example
First of all, if you want a difference between a date in a database and today's date, just do it in the database directly. You didn't specify which DB, but, for example in MySQL you'd do something like:
SELECT DATEDIFF(some_field, now()) FROM ...
If you insist on doing it in PHP, then don't use strtotime but use DateTime object:
$today = new DateTime();
$end = new DateTime($pro_deadline);
$diff = $end.diff($today)
The date() function returns a simple string, but the date_diff() function expects a date object.
You can do it all much more simply with the functions in the DateTime class:
$pro_deadline = "2018-09-01";
$today = new DateTime();
$end = new DateTime($pro_deadline);
$interval = $end->diff($today);
echo $interval->format('%R%a days');
This example outputs +25 days Click here for Runnable Demo
Further examples of the diff() function here

How to find the number of hours between two days?

So I have an array of many images in it with their datetimes in the format Y-m-d H:i:s And I wish to find the number of days between the image's date and the current date. This is where I have reached till now...and I'm getting a new error for every small change I make.
$myDateTime = DateTime::createFromFormat('Y-m-d H:i:s', $current_time);
$currentDate = $myDateTime->format('Y-m-d');
foreach($all_images as $key => $am){
$myDateTime1 = DateTime::createFromFormat('Y-m-d H:i:s', $am['datetime']);
$imageDate = $myDateTime1->format('Y-m-d');
$datediff=date_diff($currentDate,$imageDate);
echo $datediff;
}
I'm getting this error:
Warning: date_diff() expects parameter 1 to be DateTimeInterface, string given
Any help would be appreciated! Thanks a lot!
What you've done is you've converted your values to Strings before comparing them, so it's no longer comparing the difference between two dates but instead the difference between two strings. This is your error cause.
Solution:
The values you pass to date_diff need to be two DateTime objects as per the manual:
(PHP 5 >= 5.3.0, PHP 7)
DateTime::diff -- DateTimeImmutable::diff -- DateTimeInterface::diff -- date_diff — Returns the difference between two DateTime objects
Suggestion:
foreach($all_images as $key => $am){
$myDateTime1 = DateTime::createFromFormat('Y-m-d H:i:s', $am['datetime']);
$imageDate = $myDateTime1->format('Y-m-d');
$datediff=date_diff($myDateTime, $myDateTime1);
echo $datediff->format('%R%a days'); // +2 days
}
Note that the above date_diff function takes Objects not strings.
This will now use date_diff [procedurally in this example] to output a difference value $datediff which you can use with DateTime formatting to reach the number of days/hours/whatever. Please Read the manual.

Add two times of different format in PHP

In my table, I have a variable $duration which is stored in minutes.
And I also have a time variable. Let it be $time1.
$time1=date('H:i:s',$time);
$duration=1000; //minutes
$time2= secondsToTime($duration*60);
I convert the $duration to time format using the function given below.
function secondsToTime($seconds) {
$dtF = new DateTime("#0");
$dtT = new DateTime("#$seconds");
return $dtF->diff($dtT)->format('%h:%i:%s');
}
So in $time2, i have something like this stored 11:12:13
And in $time1 i have something like this stored 01:10:19
I want to perform $total=$time1+$time2;
So, I converted $time2 into time format.
$timeform= new DateTime($time2);
$newtime2= $timeform->format('H:i:s');
Now, I add $total=$time1+$newtime2;
But echo date('H:i:s',$total);gave me following error:
Notice: Object of class DateTime could not be converted to int
The second argument of date() should be a timestamp (i.e. an integer, i.e. seconds), not a formatted date string.
As far as I know only comparison operators work on datetime objects ($date1 > $date2), not math operators ($date1 + $date2).
See also http://nl3.php.net/manual/en/datetime.add.php and http://nl3.php.net/manual/en/datetime.modify.php
Use 1 datetime instance for calculating/formatting the total amount of time
Or, convert 2 datetime instances to seconds, add them, and format using date()
The second parameter of date() is expected to be a Unix timestamp as integer, not a DateTime object. (see php.net)
You need to convert your DateTime object into a Unix timestamp.
Try getTimestamp():
echo date('H:i:s',$total->getTimestamp());

Convert date into timestamp where strtotime has already been used

I' am trying to convert the date of next 7 days into timestamp so that I can compare against my date timestamp in database to get some results.
This function is used to get the next 7 days from today
$next_date = date("d/m/Y", strtotime("7 day"))
Output
30/04/2014
Now I' am again running strtotime() on $next_date variable who holds the next 7days and converting to timestamp.
echo strtotime($next_date);
This is not working. I followed this stackoverflow answer and few others.
As an alternative suggestion you could look at PHP's internal DateTime() and DateInterval() classes. It makes it a bit easier to convert between formats and do date/time addition and subtraction imho. DateInterval requires at least PHP version 5.3.
An example:
// create a current DateTime
$currDate = new DateTime();
// copy the current DateTime and
// add an interval of 7 days
$nextDate = clone $currDate;
$nextDate->add(new DateInterval('P7D'));
// both objects are easily converted to timestamps
echo $currDate->getTimestamp(); // e.g: 1398296728
echo $nextDate->getTimestamp(); // e.g: 1398901528
// and both can be easily formatted in other formats
echo $currDate->format('d/m/Y'); // e.g: 24/04/2014
echo $nextDate->format('d/m/Y'); // e.g: 01/05/2014
EDIT
For completeness, here's another example of how you can add seven days to a DateTime object:
$now = new DateTimeImmutable();
$then = $now->modify('+7 days');
var_dump($now->format('Y-m-d'), $then->format('Y-m-d'));
Yields:
string(10) "2016-05-24"
string(10) "2016-05-31"
You can also use DateTime - the difference in this use case is that DateTime::modify() will modify the instance $now where DateTimeImmutable::modify() will return a new DateTimeImmutable object - so if you need to create a new object whilst retaining the old one, it's probably the most succinct approach.
Hope this helps :)
http://www.php.net/manual/en/datetime.construct.php
http://www.php.net/manual/en/dateinterval.construct.php
Just store the value from strtotime first?
$timestamp_in_7_days = strtotime('7 day');
$next_date = date('d/m/Y', $timestamp_in_7_days);
There is no need to throw the time back and forth between unix timestamp and date-format.

php check if specified time has expired

I am trying to compare the current datetime, with a datetime from the database using string, as the following:
$today = new DateTime("now");
$todayString = $today->format('Y-m-d H:i:s');
if($todayString >= $rows["PrioritizationDueDate"])
{...}
$todayString keeps giving me the time 7 hours earlier (i.e now its 11:03pm, its giving me 16:04).
More, is it better to compare this way, or should i compare using datetime objects?
$todayString keeps giving me the time 7 hours earlier
you have to setup a timezone for the DateTime object I believe.
is it better to compare this way
I doubt so.
The general way is to compare in the query, using SQL to do all date calculations and return only matching rows.
Set a correct timezone in the constructor to DateTime.
$today = new DateTime("now", new DateTimeZone('TimezoneString'));
Where TimezoneString is a valid timezone string.
Edit: For a more complete example using DateTime objects, I would use DateTime::diff in conjunction with DateTime::createFromFormat.
$rows["PrioritizationDueDate"] = '2011-11-20 10:30:00';
$today = new DateTime("now", new DateTimeZone('America/New_York'));
$row_date = DateTime::createFromFormat( 'Y-m-d H:i:s', $rows["PrioritizationDueDate"], new DateTimeZone('America/New_York'));
if( $row_date->diff( $today)->format('%a') > 1)
{
echo 'The row timestamp is more than one day in the past from now.';
}
Demo
First set time zone using this function
date_default_timezone_set('UTC');
Then either you can use function strtotime() or get difference directly...

Categories