在SQL中使用PHP将日期转换为DATETIME [英] Converting dates with PHP for DATETIME in SQL
问题描述
我有一个PHP论坛,其日期格式如下
dd/mm/yyyy hh:mm:ss
.但是,我需要以yyyy-mm-dd hh:mm:ss
的格式将它作为SQL的DATETIME插入.如何转换这些数据?
I have a forum in PHP which takes a date like in the form
dd/mm/yyyy hh:mm:ss
. However, I need to insert it for SQL as a DATETIME in the format as yyyy-mm-dd hh:mm:ss
. How can I convert this data?
推荐答案
您的日期时间格式错误:dd/mm/yyyy hh:mm:ss
.也许您是说d/m/Y H:i:s
Your date time format is wrong: dd/mm/yyyy hh:mm:ss
. Probably you mean d/m/Y H:i:s
如果您使用的是5.3+版本,则可以使用安全的方法将日期时间转换为另一种格式.这是一个示例:
If you have 5.3+ version there is safe way to convert the date time into another format. Here's an example:
$timestamp = '31/05/2001 12:22:56';
$timestamp = DateTime::createFromFormat('d/m/Y H:i:s', $timestamp);
echo $timestamp->format('Y-m-d H:i:s');
或者,如果您喜欢更多的程序方式:
or if you like more procedural way:
$timestamp = '31/05/2001 12:22:56';
$timestamp = date_create_from_format('d/m/Y H:i:s', $timestamp);
echo date_format($timestamp, 'Y-m-d H:i:s');
请谨慎对待先前的建议.有些完全错误,另一些可能导致错误.
Be careful with previous suggestions. Some are completely wrong and others could lead to errors.
这篇关于在SQL中使用PHP将日期转换为DATETIME的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!