Returning months difference as integer - php

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

Related

PHP datetime comparison is not woking normally

Although my question seems can be found the solution on the internet easily. But I've already tried but it's not working.
I've already followed https://www.php.net/manual/en/datetime.diff.php Example #2 DateTime object comparison
or another solution like https://thevaluable.dev/php-datetime-create-compare-format/ Comparing DateTime Objects
But it is still not working.
Here is my code,
$end_time = new DateTime('2020-04-05 23:59:00');
$now = new DateTime('now');
if( $now > $end_time ){
echo 'expired!';
}
It throws the error
Object of class DateTime could not be converted to string.
Edited
I'm using PHP 7.1.23
Here is the solution for your problem. First you have to convert them into Strings then you can use them. I have changed the input date just to show you the result of if condition.
Select your City for time zone First
date_default_timezone_set('Asia/Karachi');
Your Inputs
$input_time = new DateTime('2020-04-01 23:59:00');
$now = new DateTime('now');
Convert them to string
$input_time = $input_time->format('Y-m-d H:i:s');
$now = $now->format('Y-m-d H:i:s');
The result
if( $now > $input_time )
{
echo 'expired!'. '<br>';
}
If it doesn't need to be an actual DateTime object, you could use times instead, which will then compare the same as an integer would.
Eg
$end_time = strtotime('2020-04-05 23:59:00');
$now = time();
if( $now > $end_time ) {
echo 'expired!';
}

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.

DateTime php return a wrong date

I'm using the PHP DateTime class to generate a date for a custom licensing system. While I'm debugging it, I've noted that the date time are always wrong, it will be 5-dec-2018 but now we are in November, and this date will be the same also for the expiration_date.
How i can fix this issue? I need to add 30 days to the start date of the trial period.
Here is the code.
class Activator {
private $uuid;
private $keygen;
private $licence_code;
public static function generateLicence($uuid) {
if (!file_exists(ABSPATH.'/DataStorage/.licence')) {
$start_date = new DateTime();
$time_zone = $start_date->setTimezone(new DateTimeZone('Europe/Rome'));
$trial_date = $start_date->add(new DateInterval('P30D'));
$end_date = $trial_date->format('d-M-Y');
$machine_uuid = bin2hex($uuid);
$licence_code = base64_encode($machine_uuid);
$licence_file = array(
'uuid' => $machine_uuid,
'activation_date' => $time_zone->format('d-M-Y'),
#'trial_version' => true,
#'expire_date' => $end_date,
#'licence_code' => $licence_code
);
$w = file_put_contents(ABSPATH.'/DataStorage/.licence', json_encode($licence_file));
echo $w;
}
}
This is the expected behavior, as you add() to the date (by doing $start_date->add(...) - this modifies the original object $start_date.
You can solve this a few different ways, although the easiest way is just to create a new instance entirely with the 30 days added directly in the construct. You can also set the timezone as the second parameter of new DateTime().
$timezone = new DateTimeZone('Europe/Rome');
$start_date = new DateTime("now", $timezone);
$trial_date = new DateTime("+30 days", $timezone);
PHP.net on new DateTime()
PHP.net on DateTime::add()
See this live demo.

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

DATEDIFF creating function for php code

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
}

Categories