Not getting the required date - php

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

Related

Date diffrent function showing error in my live server

here is the code of my block it gives error
$inti_date=strtotime($row->inti_date);
$inti_date=date('Y-m-d',$inti_date);
$diff=date_diff($today,$inti_date);
$temp = $diff->format("%a");
I assume you are dealing with a date from your database and want to remove the time portion from a DateTime column.
If you notice the prototype for date_diff
DateInterval date_diff ( DateTimeInterface $datetime1 , DateTimeInterface $datetime2 [, bool $absolute = false ] )
date_diff requires the dates to be of type DateTimeInterface therefore the dates need to be created using the DateTime Class
// fake an object just for testing
$row = new stdClass();
$row->inti_date = '2017-05-01 10:10:10';
$inti_date = new DateTime($row->inti_date);
// I assume you were just after the data portion in both cases
// So set time to 0 o'clock
$inti_date->setTime(0,0,0);
$today = new DateTime('now');
// set time to 0 o'clock
$today->setTime(0,0,0);
$diff = date_diff($today,$inti_date);
$temp = $diff->format("%a");
echo $temp;
// or you could code the diff processing like this
$diff = $today->diff($inti_date);
echo $diff->format("%a");
Result on 04/05/2017 is
3

Get DateTime in two fields

Getting DateTime
Hi I am not good on programming so don't judge so strong, I want to get date and time from fields.
$date_start = $this->input->post('date_start');
$time_start = $this->input->post('time_start');
$date_end = $this->input->post('date_end');
$time_end = $this->input->post('time_end');
$data['start'] = date_format('U = Y-m-d H:i:s', $date_start.' '.$time_start);
$data['end'] = date_format('U = Y-m-d H:i:s', $date_end.' '.$time_end);
Error
date_format() expects parameter 1 to be DateTimeInterface, string given
Try like this
$data['start'] = date_format(date_create( $date_start.' '.$time_start),"U = Y-m-d H:i:s");
The function date_format expects an object implementing DateTimeInterface as the first argument and the format string as the second argument.
You can create a DateTime object from a string with it's factory method DateTime::createFromFormat also procedurally with date_create_from_format documented on the same page.

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.

php Object of class DateInterval could not be converted to string

i've tried using date_diff and date_create to get a difference from two date that's already converted to string.
here's the code:
$date_1 = date_create();
$date_now = date_format($date_1, 'Y-m-d');
//echo $date_now . "\n";
$date=date_create($date_now);
date_add($date,date_interval_create_from_date_string("3 days"));
$date_return = date_format($date,"Y-m-d");
$diff = date_diff(date_create($date_now), date_create($date_return));
echo $diff;
and i am getting this error:
Object of class DateInterval could not be converted to string
You need to call DateInterval::format() to display that difference as a string.
echo $diff->format('%d days');
See the manual for all of the available formatting options.
Using Carbon(A simple PHP API extension for DateTime) could be something like this
$date_now->diffInDays($date_return);
hope this helps. But to get more information about Carbon follow this link Carbon Docs

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