Convert php datetime format to mysql error

I am having trouble inserting datetime $_POST into mysql. I am getting an error of:

Warning : date_format() expects parameter 1 to be DateTime, string given in

I have tried various options but either get error or enters 1970. I would be grateful if someone could point out my error. Here is the value and format that is being passed for conversion:

06/02/2019 14:45:49 PM

$intakedate = $_POST['frtvdatetimepicker'];
$date = date_create(str_replace('/','-', $intakedate));
$intakedate = date_format($date, 'Y-m-d H:i:s');

The PM in that date is weird. It’s either 2:00PM or 14:00, but not 14:00 PM. Can you get rid of the PM in the input?

Anyway, this works:

$intakedate = '06/02/2019 14:45:49 PM';

// remove next line if you can remove "PM" from the input somewhere else
$intakedate = str_replace(' PM', '', $intakedate);

$intakedate = DateTime::createFromFormat('d/m/Y H:i:s', $intakedate)->format('Y-m-d H:i:s');

2 Likes

@rpkamp
Thank you very much. You sir are a lifesaver.

Should this work with php 5.3.1? as it is throwing an error of:

Fatal error: Call to a member function format() on a non-object

Many thanks

No one should work with 5.3.1

It has reached its End Of Life so long ago it isn’t even on the chart

EOL means it doesn’t get bug, security or critical security fixes. Nada, zip, zilch

A release that is no longer supported. Users of this release should upgrade as soon as possible, as they may be exposed to unpatched security vulnerabilities.

True, there is nothing saying everyone should be on the absolute latest release version. And I realize setting up a development environment isn’t always an enjoyable experience. IMHO you should take the “as soon as possible” seriously, and make the effort to upgrade to a version that is still supported.

If you are having problems upgrading please start a topic asking for help. There are different ways to set up development environments, and someone else’s preferred way may not be your preferred way, but you really should upgrade as soon as possible.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.