How to find the number of hours between two days? - php

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.

Related

DateTime Comparison with objects 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

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

Convert number to date in PHP and format to YYYYMMDD [duplicate]

This question already has answers here:
PHP remove dots and hyphens
(5 answers)
Closed 3 years ago.
I want to convert date from, for example, 1441065600 to YYYYMMDD format. How do I do that?
$temp = date("Y-m-d",1441065600);
$rel_date = date_format( $temp, "YYYYMMDD");
The code above gives an error:
date_format() expects parameter 1 to be DateTimeInterface
Using date()
Simply write:
<?php
echo date('Ymd', 1441065600);
Otherwise, using a DateTime instance:
Short
<?php
echo (new DateTime())->setTimestamp(1441065600)->format('Ymd');
Note: the setTimestamp() method do not takes a string as parameter! Otherwise, you may want to do so:
Long
<?php
$english = '1441065600';
$timestamp = strtotime($english);
$date = new DateTime($timestamp);
echo $date->format('Ymd'); // 20161214
Descriptions
strtotime() - Parse about any English textual datetime description into a Unix timestamp
DateTime - Representation of date and time
Note: I created a new DateTime instance from the UNIX timestamp, English textual representation may lead to an error.
Other formats
I recommend you to read the DateTime::format() method documentation along with the date() function documentation to learn more about date formats.
$date = (new DateTime())->setTimestamp(1441065600);
echo $date->format('Ymd');
date_format is function in which first argument should be DateTime object, date function return string.
So first You need to create correct object.
$date = new DateTime(strtotime(1441065600));
and then format it with date_format
echo date_format($date,'Ydm');
You can pass the timestamp to the DateTime constructor by prepending # character:
$d = new DateTime('#1441065600');
echo $d->format("Ymd");
See Compound Formats.
Use Date function in PHP
echo $temp = date("Y-m-d",1441065600);
Result:
2015-09-01
Refer http://php.net/manual/en/function.date.php

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