Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

mysqli - Converting dates with PHP for DATETIME in 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your date time format is wrong: dd/mm/yyyy hh:mm:ss. Probably you mean d/m/Y H:i:s

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...