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

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

Related

PHP: Get timestamp from date format YYYY-MM-DD HH:MM:SS GMT+HH:MM

I'm reading lines from a *.txt file and get strings (date formats) in this style:
2017-10-19 20:51:54 GMT+08:00
2020-03-31 13:19:31 GMT-08:00
2018-04-10 14:35:17 GMT
With the function DateTime::createFromFormat, I want to convert such lines into a time string. After that, I would like to get the timestamp with getTimestamp();. So, currently my code looks like this ($date is my read line):
$date = DateTime::createFromFormat("Y-m-d H:i:s", $date);
$timeStamp = $date->getTimestamp();
When I try to do this, I get this error message:
Fatal error: Uncaught Error: Call to a member function getTimestamp() on bool in ...
Does anyone have an idea how to solve this problem?
Edit:
Regarding Gordon's comment, I also tried to add the missing parts ("GMT" => e and "+08:00" => P) as well, like this:
$date= DateTime::createFromFormat("Y-m-d H:i:s eP", $date);
You are getting this error because the date provided does not match the format specified.
Add the following line after createFromFormat() call -
var_dump(DateTime::getLastErrors());
The above line will return the error. The error message is - "Trailing data". This is because of "GMT+08:00" in the string.
For processing it properly you should provide the optional third parameter to createFormFormat which is timezone and it expects it to be a DateTimeZone object. So update your createFromFormat function as -
$timezone = new DateTimeZone('GMT+08:00');
$date = "2017-10-19 20:51:54";
$date = DateTime::createFromFormat("Y-m-d H:i:s", $date, $timezone);
I hope this helps. You will have to separate the date from the timezone and process it as mentioned above.

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

getting difference between two dates in php giving error

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

How to add days to a date with a certain format? [duplicate]

This question already has answers here:
Add number of days to a date
(20 answers)
Closed 7 years ago.
I know this was asked before, but I looked at all those solutions and they don't work for me. Theirs start with a format that I'm not starting with, but even so I tried their solutions anyway and I kept getting a 1970 year as my end date.
So I have a start date in the format of mm-dd-YYYY, and I want to add 35 days to it to create an end date. The following is what I finally was able to make work, but it's inconsistent, or maybe I was wrong and it doesn't really work.
I convert the start date to YYYY-mm-dd because that's what i noticed works better with the strtotime function. I tried converting it differently but nothing worked except doing it the explode way.
So after format conversion then adding the days and converting format back, for some reason it adds like 49 days, even though I am specifying 35 days.
I don't know what else to try.
$startdate = "08-13-2015";
$pieces = explode("-", $startdate);
$newdate = $pieces[2]."-".$pieces[0]."-".$pieces[1];
$enddate = date('m-d-Y', strtotime($newdate. ' + 35 days'));
echo $enddate; //result is 10-01-2015 when it should be 09-17-2015
UPDATE
modified for my need. using variable as the start date.
$inputdate = new DateTime($startdate);
$inputdate->modify('+35 days');
$enddate = $inputdate->format('m-d-Y');
Get the following errors when the page with the code is ran:
Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (08-13-2015) at position 0 (0): Unexpected character' in path\file.php on line 9002
Exception: DateTime::__construct(): Failed to parse time string (08-13-2015) at position 0 (0): Unexpected character in path\file.php on line 9002
9002 says this:
$inputdate = new DateTime($startdate);
DateTime with DateTime::modify() should do it, as shown.
$date = new DateTime('08-13-2015');
$date->modify('+35 days');
echo $date->format('m-d-Y');
But check your PHP version first, if it's below 5.1 you won't be able to use it and under 5.3 you'll face some minor bugs.
you can do it with mktime
$startdate = "08-13-2015";
$pieces = explode("-", $startdate);
$newdate2 = mktime(12, 0, 0, $pieces[0], $pieces[1] + 35, $pieces[2]);
$enddate2 = date('m-d-Y', $newdate2);
var_dump($enddate2); // 09-17-2015
you need to read this
http://php.net/manual/en/book.datetime.php
or use a date library like carbon
https://github.com/briannesbitt/Carbon

Categories