Push strangely formatted dates into MySQL from PHP
-
09-10-2019 - |
문제
I am sure this must be a common question but I cannot find it anywhere so here it goes:
I have dates in this format: 09/Jul/2003:00:03:48 -0300
and I want to push them into a DATETIME
field in MySQL.
What is the easiest way to do this? Pushing them in as is results in them being zeroed.
해결책
MySQL doesn't include the timezone in DATETIMEs, but you can use:
STR_TO_DATE('09/Jul/2003:00:03:48', '%d/%b/%Y:%H:%i:%s')
...to convert a string representation of a date/time into a DATETIME for storing in the database.
Reference:
다른 팁
As far as I know can not be changed and has to be in the format below:
'YYYY-MM-DD HH:MM:SS'
My favorite function in all of PHP is strtotime()
. If that can't interpret the input then I probably can't code something that could.
So I would do something like:
mysql_real_escape_string(date('Y-m-d H:i:s', strtotime($stragely_formatted_date)));
to prepare a DATE string to give to MySQL.
As always, think about timezones in your the design.
The mysql_real_escape_string()
is probably unnecessary but I always feel more secure when I use it.