getting difference between two dates in php giving error - php

i am trying to find difference between two dates in php, the first date is coming from my database (which is in datetime format), so i am converting it to date and then finding the difference using the current date. my code is like below:
$ret=mysqli_query($con,"select * from members");
$cnt=1;
while ($row=mysqli_fetch_array($ret))
{
$date_time = $row['date'];
$new_date = date("Y-m-d",strtotime($date_time));
$dates = date('Y-m-d');
$diff = $new_date->diff($dates);
echo $diff;
}
then i am getting the following error:
Uncaught Error: Call to a member function diff() on string in C:\xampp\htdocs\form\admin\members.php:123 Stack trace: #0 {main} thrown in C:\xampp\htdocs\form\admin\members.php on line 123
can anyone please tell me what i am doing here is wrong. thanks in advance

date function returns a string.
https://www.php.net/manual/en/function.date.php
You can use date_diff function to compare dates in string format
https://www.php.net/manual/en/function.date-diff.php
or use DateTime class which has method diff.
https://www.php.net/manual/en/class.datetime.php

Use date_diff function instead of the object notation here, DateTime object if you want your date to be Object

date() function returns a string. You need to create an object of DateTime class. Your loop should look something like this:
foreach ($ret as $row) {
$new_date = new \DateTime($row['date']);
$diff = $new_date->diff(new \DateTime());
var_dump($diff);
}

Related

PHP - DateTime::__construct(): Failed to parse time string

I am pulling DateTime timestamp result from another table which is set as:
When dumping specific value of $post->getUploadTime() I get:
"2602585961"
It's in string format.
In my entity I have modified the setter to:
public function setStartTime($startTime)
{
$date = new \DateTime($startTime);
$this->startTime = $date->getTimestamp();
return $this;
}
And my code:
$newEntityObject->setStartTime(intval($post->getUploadTime()));
I am using intval() to transform string to integer (timestamp) so I can insert it in db but I get an error:
DateTime::__construct(): Failed to parse time string (2602585961) at position 8 (6): Unexpected character"
It's an error with or without the intval().
I can not figure out what is wrong?
I know there are a lot of posts about the issue. I tried them, but the problem still remains.
Try :
$date = new \DateTime();
$date->setTimestamp($startTime);
$this->startTime = $date->getTimestamp();
But since you are trying to assign a timestamp to your startTime property and you are already passing a timestamp to your function you can just assign whatever timestamp you are passing:
$this->startTime = $startTime;
You have a timestamp, and you are trying to make it a DateTime and get timestamp from the new datetime object.
The DateTime constructor only accept specific date and time format.
Also, the given value refer to the year 2052. So it's possible that you have another issue before.
You don't need to convert to a number. Because you need a string argument that starts with #
You need use #. Read Documentation.
<?php
$a = "#2602585961";
function setStartTime($startTime)
{
$date = new \DateTime($startTime);
$b = $date->getTimestamp();
return $b;
}
echo setStartTime($a);
https://www.php.net/manual/ru/datetime.formats.compound.php
In your code:
$newEntityObject->setStartTime("#" . $post->getUploadTime());

PHP date_create_from_format using with object giving bool(false) error

I am trying to use the PHP date_create_from_format on an object so I can use the diff() function to calculate the number of days from when the record was created to today (whenever that is looked at)
If I echo $job->created_date I get something like 2021-2-27 10:05:00
I started with:
$created = $job->created_date;
$date_now = date('Y-m-d');
$job_posted_date_difference = $date_now->diff($created); <<< the error shows on this line
echo $job_posted_date_difference.$difference->d.' days';
but I get a fatal error Call to a member function diff() on string
So....... I thought that it could be a formatting of the initial date issue and then I tried
$created = date_create_from_format('Y-m-d', $job->created_date);
$date_now = date('Y-m-d');
var_dump ($created);
But the dump shows - bool(false)
How do I fix this properly? I looked at a number of other SO issues and they seemed to really range from the dates being in the wrong order( I tried both ways) to the formatting issue .
and if you want to calculate days from two dates
then you can use
$ceated_date = "2021-2-27 10:05:00";
//create a date object of created date and get timestamp.
$t1 = (new DateTime($created_date))->getTimetamp();
//create a date object of now and get timestamp.
$t2 = (new DateTime("now"))->getTimestamp();
//this will give you days
$day_diff = floor(($t2 - $t1) / 86400);

Uncaught Exception: DateTime::__construct(): Failed to parse time string

I'm using the function below to calculate the age (in years) of people from birthdays dates (in european format DD/MM/YYYY) that are stored as text in Wordpress Advanced Custom Fields
function get_age($birthDate_old) {
$birthDate = ($birthDate_old);
return date_diff(new DateTime($birthDate), new DateTime('today'))->y;
}
In the majority of cases it works fine but in some cases I got the error below :
Fatal error: Uncaught Exception: DateTime::__construct(): Failed to parse time string (26/01/1958) at position 0 (2): Unexpected character in /home/XXXX/functions.php:99 Stack trace: #0 /home/XXXX/functions.php(99): DateTime->__construct('26/01/1958') #1 /home/XXXX/single.php(69): get_age('26/01/1958') #2 /home/XXX/wp-includes/template-loader.php(98): include('/home/XXX/...') #3 /home/XXX/wp-blog-header.php(19): require_once('/home/XXX/...') #4 /home/XXX/index.php(17): require('/home/monmaire/...') #5 {main} thrown in /home/XXXX/functions.php on line 99
Example of data that works fine :
$age = get_age($birthday);
For $birthday value = 05/04/1946 it works fine but for $birthday value = 26/01/1958 I get the error above.
I don't undertand why as the data seems to me the same format in the 2 cases.
Do you have any clue why ?
Thanks.
Regards.
I fix your function like this :
function get_age($birthDate_old) {
return date_diff(
DateTime::createFromFormat('d/m/Y', $birthDate_old),
new DateTime('today')
)->y;
}
In your case your date is malformated since DateTime constructor doesn't know if you pass a month or a day.
05/04/1946 is ok.
26/01/1958 is not ok because 26 represent month by default.
According to this:
https://www.php.net/manual/en/datetime.formats.php
// THIS IS INVALID, WOULD IMPLY MONTH == 19
$external = "19/10/2016 14:48:21";
// HOWEVER WE CAN INJECT THE FORMATTING WHEN WE DECODE THE DATE
$format = "d/m/Y H:i:s";
$dateobj = DateTime::createFromFormat($format, $external);
$iso_datetime = $dateobj->format(Datetime::ATOM);
echo "SUCCESS: $external EQUALS ISO-8601 $iso_datetime";
26 is treated as month. So, add $format = "d/m/Y"; to your date like above.
Problem is the date format. I believe you are switching between "/" and "-". If you are dealing with large data, it will be difficult to have to fix the whole database so my best advise is to do a preg_replace in order to always make sure what you are taking from the user/DB is in a correct format. Find example code below.
function get_age($birthDate_old) {
$birthDate = ($birthDate_old);
return date_diff(new DateTime($birthDate), new DateTime('today'))->y;
}
$birthDate = "26/01/1958";
$birthDate = preg_replace("(/)", "-", $birthDate);
echo get_age($birthDate);
I hope it helps! Let me know

Trying to add 2 dates with DateTime Object PHP

Hi there and thank you for the help. I will try to be breef.
I have a SQL table with one col named "duration" -> type Time
I need to get this "duration" and add to the actual DateTime -> date()
Till now I got something like these:
$id_mission = $_POST["id_mission"];
$sql="SELECT duration FROM missions WHERE id_mission='".$id_mission."'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
How do i pick this: $row['duration'] and convert to DateTime Object?
$date = new DateTime();
$get_datetime = $date->format('Y-m-d H:i:s');
$get_datetime->add(new DateInterval($row['duration']));
I got these sql error:
Fatal error: Call to a member function add() on string in C:\wamp64\www\players\actions\insert_mission.php on line 18
This line converts your DateTime object into a string which you are then trying to call the add() method with. Strings don't have this method.
$get_datetime = $date->format('Y-m-d H:i:s');
To add the date from your row don't use the format method.
$date = new DateTime();
$date->add(new DateInterval($row['duration']));
The error message that you are seeing has nothing to do with SQL, it is telling you that your are trying to treat a string like an object. Which doesn't work in PHP.

"Call to a member function format() on a non-object" when converting date in PHP

I can not get rid of this error message:
Call to a member function format() on a non-object
So, I go on googling and get some good source like this StackOverflow question.
I tried to do something similar, but I failed. This is my code :
$temp = new DateTime();
/*ERROR HERE*/ $data_umat['tanggal_lahir'] = $data_umat['tanggal_lahir']->format('Y-m-d');
$data_umat['tanggal_lahir'] = $temp;
So, i did trial & errors, and I found out if I do this:
$data_umat['tanggal_lahir'] = date("Y-m-d H:i:s");
The date will successfully converted, BUT it always return today's date (which i dont want).
I want to convert the date so that 10/22/2013 will be 2013-10-22.
You are calling method format() on non-object. Try this:
$data_umat['tanggal_lahir'] = new DateTime('10/22/2013');
$data_umat['tanggal_lahir'] = $data_umat['tanggal_lahir']->format('Y-m-d');
or one-liner:
$data_umat['tanggal_lahir'] = date_create('10/22/2013')->format('Y-m-d');
You can use strtotime() to convert this. Its converts the given date to a timestamp and then by using date() function you can convert the timestamp to desired date format.
Try this..
$date = '10/22/2013';
$timestamp = strtotime($date);
$new_date = date('Y-m-d',$timestamp );
$data_umat['tanggal_lahir'] is not an instanceof of object DateTime
use to make it instance of DateTime
$data_umat['tanggal_lahir'] = new DateTime();
$data_umat['tanggal_lahir'] is not an instance of DateTime, however $temp is.
Is $data_umat['tanggal_lahir'] meant to be be an instance of DateTime
$temp = new \DateTime(); (need \ )
/*ERROR HERE*/ $data_umat['tanggal_lahir'] = $data_umat['tanggal_lahir']->format('Y-m-d');
$data_umat['tanggal_lahir'] = $temp;
when using Symfony or Slim with Doctrine, try this:
//form[birthday = "2000-12-08"]
[...]
$birthday = \DateTime::createFromFormat("Y-m-d",$formData['birthday']);
$obejct = new $object();
$object->setBirthday($birthday);
[...]
If you encounter this issue when using Symfony, try this hack:
Open:Your Symfony Root/vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/DateTimeType.php
Go to line 50 something where the function convertToDatabaseValue() is declared.
The original code:
return ($value !== null)
? $value->format($platform->getDateTimeFormatString()) : null;
Change to:
return ($value !== null)
? $value : null;
Seems Symfony is doing an extra conversion when passing a string as the datestring.
Directly passing a DateTime ojbect won't work as it will prompt another error saying "Object DateTime can't be converted to string".

Categories