Inserting dates into an SQL database using PHP [duplicate] - php

Crashes on:
<?php
$date = "13-06-2015 23:45:52";
echo Datetime::createFromFormat('d-m-Y h:i:s', $date)->format('Y-m-d h:i:s');
?>
PHP Fatal error: Call to a member function format() on boolean
But with other dates works well:
<?php
$date = "10.06.2015 09:25:52";
echo Datetime::createFromFormat('d-m-Y h:i:s', $date)->format('Y-m-d h:i:s');
?>
Wrong format?

Neither example work as you have multiple errors:
You forgot your second parameter to Datetime::createFromFormat()
h:i:s should be H:i:s
Your date in the second example is separated by a . not a -
Fixes:
<?php
$date = "13-06-2015 23:45:52";
echo DateTime::createFromFormat('d-m-Y H:i:s', $date)->format('Y-m-d h:i:s');
$date = "10.06.2015 09:25:52";
echo DateTime::createFromFormat('d.m.Y H:i:s', $date)->format('Y-m-d h:i:s');
?>

In my case I was getting this error because I was using microtime(true) as input:
$now = DateTime::createFromFormat('U.u', microtime(true));
In the specific moments where microtime returns a float with only zeros as decimals, this error appeared.
So I had to verify if its decimals and add a decimal part:
$aux = microtime(true);
$decimais = $aux - floor($aux);
if($decimais<=10e-5) $aux += 0.1;
$now = DateTime::createFromFormat('U.u', $aux);
EDIT:
Due to floating point precision sometimes floor brings an incorret floor, so I had to use a more straight forward approach:
$aux = microtime(true);
$now = DateTime::createFromFormat('U.u', $aux);
if (is_bool($now)) $now = DateTime::createFromFormat('U.u', $aux += 0.001);

While others try to get this question answered with a specific use case, I think it's time to wrap it up with a general answer.
Fatal error: Uncaught Error: Call to a member function format() on bool in path/to/source/code/file.php
When this exception error is raised, it's because the format() function gets a bad date format string. So, try to check the parameter according to https://www.php.net/manual/en/datetime.createfromformat.php#format

In my case, I sent an empty value from the input field and get's error
solution:
if ($this->input->post('date_fo_return') != "") {
$date_fo_return = $this->input->post('date_fo_return');
$date_fo_return2 = DateTime::createFromFormat('d/m/Y', $date_fo_return);
$data['date_fo_return'] = $date_fo_return2->format("Y-m-d H:i:s");
}

John Conde's answer is correct. If we forget the mistakes, the error occurs because the supplied input doesn't mach the format string.
Example:
DateTime::createFromFormat('D M j h:i:s e Y','Fri Nov 4 12:59:59 UTC 2022');
will return a DateTime object while following will return false.
DateTime::createFromFormat('D M j h:i:s e Y','Fri Nov 4 13:00:01 UTC 2022');
The culprit is the letter 'h' of the format string 'D M j h:i:s e Y'. For 12 hour format, which 13:00:01 is, you have to use the upper case 'H'.
If you look at the documentation, you can see the difference.
h: 12-hour format of an hour with leading zeros
H: 24-hour format of an hour with leading zeros

Basically if you look at this function Datetime::createFromFormat, you will find that function has 2 possible return values, they are DateTime object and false.
That fatal error happened because you call function format on false value which is invalid.
So you should check for return value first, then continue the process appropriately. Not only for this case (datetime), but also for another functions that have multiple possible return values.

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.

Converting a non standard date string to a mysql datetime string using php

My intention is to convert the following date
20/04/17 13:27:5
to this
20-04-2017 13:27:05
I tried the typical date format functions of php and also Carbon...
things like
$newDate= Carbon::createFromFormat('d/m/y H:m:s', $originalDate);
in this case
var_dump($newDate->toDateTimeString()) would bring 2019-03-20 13:00:55 which is not what I expect.
So I was not lucky....is there a way to do this in a straight forward manner?
I think this should work.
$date = "20/04/17 13:27:5";
$sec = substr($date, strrpos($date, ":") + 1);
$sec = substr("0{$sec}", -2);
$new = substr($date, 0, strrpos($date, ":") + 1) . $sec;
$newDate = Carbon::createFromFormat('d/m/y H:i:s', $new);
I changed the format since you were using m twice for "minutes" and "month". It is correct for the month, but not for the minutes. Instead use i for minutes with leading zeroes.
$sec Is what I used to get the second from the string. This gets the last position of : and will take everything after it. This assumes that you do not change the format of the string.
substr("0{$sec}", -2) Adds a zero to the current second and extracts the last two characters. That means that 50 becomes 050 and then the last two characters are 50 so we end up without the padding, but 5 becomes 05 and the last two characters are the only characters.
$new concatenates the start of the date string and the new second with the zero padding.
$newDate is your original string with the format changed.
There is issue with seconds. There must be 05 not only 5
<?php
$original_date = "20/04/17 13:27:5";
$date_explode = explode(":", $original_date);
$date_explode[2] = str_pad($date_explode[2],2,"0",STR_PAD_LEFT);
$original_date = implode($date_explode,":");
$date = DateTime::createFromFormat('d/m/y H:i:s', $original_date);
echo date_format($date,"d-m-Y H:i:s");
?>
This is a working conversion routine that creates the ISO format you are looking for. But as already mentioned you need to "fix" the strange way the seconds are specified in the original example you provide. You will have to use string functions if that really is the format you receive. Better would be to fix the code that creates such broken formats.
<?php
$input = '20/04/17 13:27:05';
$date = DateTime::createFromFormat('d/m/y H:i:s', $input);
var_dump($date->format('d-m-Y H:i:s'));
The output obviously is:
string(19) "20-04-2017 13:27:05"
Isn't it like this?
$newDate = Carbon::createFromFormat('d/m/y H:i:s', $originalDate);

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.

Having trouble to convert a string date to a date object

This is the current date I got in PHP from getLastLogin():
Apr 22 2016, 01:44:17 CEST
This is the code that I use to convert it:
$ymd = null;
$dateObject = DateTime::createFromFormat('M d Y, H:i:s T', $player->getLastLogin());
if($dateObject){ $ymd = $dateObject->format("m/d/Y"); }
echo $ymd;
There is no error but it never goes into the if statement and therefore it's still null when I try to echo it.
My function getLastLogin() is working as well, so I think it's narrowed down to the actual format.
Thanks for help!

PHP Fatal error: Call to a member function format() on boolean

Crashes on:
<?php
$date = "13-06-2015 23:45:52";
echo Datetime::createFromFormat('d-m-Y h:i:s', $date)->format('Y-m-d h:i:s');
?>
PHP Fatal error: Call to a member function format() on boolean
But with other dates works well:
<?php
$date = "10.06.2015 09:25:52";
echo Datetime::createFromFormat('d-m-Y h:i:s', $date)->format('Y-m-d h:i:s');
?>
Wrong format?
Neither example work as you have multiple errors:
You forgot your second parameter to Datetime::createFromFormat()
h:i:s should be H:i:s
Your date in the second example is separated by a . not a -
Fixes:
<?php
$date = "13-06-2015 23:45:52";
echo DateTime::createFromFormat('d-m-Y H:i:s', $date)->format('Y-m-d h:i:s');
$date = "10.06.2015 09:25:52";
echo DateTime::createFromFormat('d.m.Y H:i:s', $date)->format('Y-m-d h:i:s');
?>
In my case I was getting this error because I was using microtime(true) as input:
$now = DateTime::createFromFormat('U.u', microtime(true));
In the specific moments where microtime returns a float with only zeros as decimals, this error appeared.
So I had to verify if its decimals and add a decimal part:
$aux = microtime(true);
$decimais = $aux - floor($aux);
if($decimais<=10e-5) $aux += 0.1;
$now = DateTime::createFromFormat('U.u', $aux);
EDIT:
Due to floating point precision sometimes floor brings an incorret floor, so I had to use a more straight forward approach:
$aux = microtime(true);
$now = DateTime::createFromFormat('U.u', $aux);
if (is_bool($now)) $now = DateTime::createFromFormat('U.u', $aux += 0.001);
While others try to get this question answered with a specific use case, I think it's time to wrap it up with a general answer.
Fatal error: Uncaught Error: Call to a member function format() on bool in path/to/source/code/file.php
When this exception error is raised, it's because the format() function gets a bad date format string. So, try to check the parameter according to https://www.php.net/manual/en/datetime.createfromformat.php#format
In my case, I sent an empty value from the input field and get's error
solution:
if ($this->input->post('date_fo_return') != "") {
$date_fo_return = $this->input->post('date_fo_return');
$date_fo_return2 = DateTime::createFromFormat('d/m/Y', $date_fo_return);
$data['date_fo_return'] = $date_fo_return2->format("Y-m-d H:i:s");
}
John Conde's answer is correct. If we forget the mistakes, the error occurs because the supplied input doesn't mach the format string.
Example:
DateTime::createFromFormat('D M j h:i:s e Y','Fri Nov 4 12:59:59 UTC 2022');
will return a DateTime object while following will return false.
DateTime::createFromFormat('D M j h:i:s e Y','Fri Nov 4 13:00:01 UTC 2022');
The culprit is the letter 'h' of the format string 'D M j h:i:s e Y'. For 12 hour format, which 13:00:01 is, you have to use the upper case 'H'.
If you look at the documentation, you can see the difference.
h: 12-hour format of an hour with leading zeros
H: 24-hour format of an hour with leading zeros
Basically if you look at this function Datetime::createFromFormat, you will find that function has 2 possible return values, they are DateTime object and false.
That fatal error happened because you call function format on false value which is invalid.
So you should check for return value first, then continue the process appropriately. Not only for this case (datetime), but also for another functions that have multiple possible return values.

Categories