DATEDIFF creating function for php code - php

I am trying to convert the following MYSQL SELECT code in to php code: DATEDIFF(date, NOW()) <= 31 basicaly if the date is less than or equal to 31 days do the rest.
So far what I have done is the following
$today = new DateTime('now');
$date = $row['date'];
$diff = date_diff($date,$today);
and than inside if cycle I have the condition: if ($diff <= 31)
My Sql date column is only specified as a Date not DateTime I am getting the following error and I am wondering how I can get calculated the date only
Warning: date_diff() expects parameter 1 to be DateTime, string given in D:\xampp\htdocs\website\c.php on line 299
bool(false)
Warning: date_diff() expects parameter 1 to be DateTime, string given in D:\xampp\htdocs\website\c.php on line 299
bool(false)
Aditional Information which makes the answers bellow to not be working is that in my SQL query I am preformating the date with DATE_FORMAT(date,'%d %b %Y') as date
Any help will be very welcome. Thanks!

You need to convert the database data to a DateTime object as well before you do date_diff() on it.
$today = new DateTime('now');
$date = new DateTime($row['date']);
$diff = date_diff($date,$today);
Now realize that since $diff is a DateInterval object, and you only care about the days component, you can evaluate like this:
if ($date->days <= 31) {
// do something
}

Try:
$today = new DateTime('now');
$date = new DateTime($row['date']);
$diff = $date->diff($today)->days;
date_diff expects both arguments to be DateTime objects. Thats what it is complaining about.
date_diff or Datetime::diff return a DateInterval, you can get the days from the days member variable

Here is the algorithm:
$then = new DateTime('2010-05-30');//example, you could use $row['date']
$now = new DateTime();//now
$delta = $now->diff($then);
$data = array(
'year' => $delta->y,
'month' => $delta->m,
'day' => $delta->d,
'hour' => $delta->h,
'minute' => $delta->i,
'second' => $delta->s
);
//now
if($data['day'] <= 31)
{
//do the stuff
}

Related

How to add time of timeType to DateTimeType

I want to add variable of type TimeType to a variable of DateTimeType
I have triying this code :
$newDate = $dateAppointment->add($duration);
but i got this error
Warning: DateTime::add() expects parameter 1 to be DateInterval,
object given
Examples of data:
$dateAppountment = 2019-03-21 10:15:00
$duration : 00:15:00
I suppose there's some kind of transformer already exists in symfony, but I can't find it. So, here's a custom code how to convert time from DateTime to DateInterval and add it to another \DateTime:
$dateAppointment = (new \DateTime());
$dtDuration = (new \DateTime())->setTime(1, 15, 0);
$duration = $duration->format('\P\TH\Hi\Ms\S');
$newDate = $dateAppointment->add(new \DateInterval($duration));
Fiddle: https://3v4l.org/5lFlQ
Here is an example:
$duration = '1970-01-01 01:00:00.000000';
$timeObject = DateTime::createFromFormat('Y-m-d H:i:s.u', $duration, new DateTimeZone('UTC'));
$date = '2019-03-21 10:15:00';
$dateObject = DateTime::createFromFormat('Y-m-d H:i:s', $date);
$modify = '+' . $timeObject->format('U') . ' second';
echo $dateObject->modify($modify)->format('Y-m-d H:i:s');
Just get the seconds from your duration object and add them to your date object. If you used modify, there are a lot of things you can do.

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

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

How to compare a datetime to a datetime + X hours with PHP?

I got 2 datetimes objects. One is the current datetime. The otherone is when the user Checked in. To which I'd like to add 6 hours.
I first initialize the current datetime:
$now=date("Y-m-d H:i:s");
Then I'm using datediff but I don't now how to add 6 hours, I assume I would have to use modify, but i don't understand how to use it.
$datetimeIn = date_create($result->getDateCheckIn());
$datetimeOut = date_create($now);
date_modify($datetimeOut, '+6 hours');
$interval = date_diff($datetimeIn, $datetimeOut);
if ($interval->format('%a minute') > 0)
$UsersToCheckOut[] = $result;
Can somebody help me figuring howw to add X hours to a datetime to compare it to another ?
I got this error:
date_create() expects parameter 1 to be string, object given in line date_modify($datetimeOut, '+6 hours');
Thanks
I'm going to attempt to answer both your title and the question I inferred you were asking from the body of your question.
The PHP manual is very clear on actually comparing datetimes. Here's example code for that:
$date1 = new DateTime("now");
$date2 = new DateTime("+6 hours");
var_dump($date1 == $date2);
var_dump($date1 < $date2);
var_dump($date1 > $date2);
//bool(false)
//bool(true)
//bool(false)
The part where you actually add 6 hours is also correct. I copied your code and tested it see if I could get the same error as you. I did when my $datetimeIn parameter was bad. Based off that and the error you posted, it looks very much like the problem lies in your $datetimeIn parameter. I copied my working code below:
$now=date("Y-m-d H:i:s", strtotime('2013-04-15 04:00:0'));
$datetimeIn = date_create($now);
$datetimeOut = date_create($now);
date_modify($datetimeOut, '+6 hours');
$interval = date_diff($datetimeIn, $datetimeOut);
if ($interval->format('%a minute') > 0) {
echo "success";
} else {
echo "fail";
}
According to the error message, it is happening because in your line "$datetimeOut = date_create($now);", the variable $now exists and is some kind of object; date_create() requires the first argument to be some kind of string. See documentation about the valid date and time formats here
You can get a copy, with an offset of 6 hours, like this:
$now = date_create('now');
$future = date_modify(clone $now, '+ 6 hours');
$diff = date_diff($now, $future);
var_dump($diff);die;
$datetimein = date("m/d/Y H:i:s");
$datetimeout = date("m/d/Y H:i:s", strtotime($datetimein) + 6 * 60 * 60);
see it working live: http://codepad.viper-7.com/6wn8dK

Returning months difference as integer

I am trying to return month difference as integer and call if to table column. My code:
function ETA($ArrivalDate, $pattern = 'mysql'){
$patterns = array(
'eu' => 'd/m/Y',
'mysql' => 'Y-m-d',
'us' => 'm/d/Y',
);
$CurrentDate = date("Y-m-d");
$ArrivalDate = $variants_data['ArrivalDate'];
$diff = $ArrivalDate->diff($CurrentDate);
return $diff->y;
}
The I call it with
<td>'.$_GET['ETA'].'</td>
But there is nothing returned, what am I doing wrong here?
You can get what you want in a simpler approach using the DateTime object in PHP:
function ETA($ArrivalDate){
$currentDate = new DateTime();
$arrivalDate = new DateTime($ArrivalDate);
$interval = $currentDate->diff($arrivalDate);
return $interval->format('%m');
}
See working example: http://3v4l.org/UlPQo
If you don't pass in an appropriate format $ArrivalDate you will get an exception thrown, so you need to wrap the call in a Try/Catch.
See DateTime Interval Format for more on the return value.
Try this simple one
<?php
//for months
$monthdiff=floor((abs(strtotime(date("d/m/Y")) - strtotime($ArrivalDate))/(60*60*24*30)));
//for days
$daydiff=floor((abs(strtotime(date("d/m/Y")) - strtotime($ArrivalDate))/(60*60*24)));
?>

Categories