問題描述
我有一個 PHP 論壇,它采用的日期形式為dd/mm/yyyy hh:mm:ss
.但是,我需要將其作為 DATETIME 以 yyyy-mm-dd hh:mm:ss
格式插入到 SQL 中.如何轉換這些數據?
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.
這篇關于使用 PHP 將日期轉換為 SQL 中的 DATETIME的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!