使用 PHP 将日期转换为 SQL 中的 DATETIME

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10688340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:49:24  来源:igfitidea点击:

Converting dates with PHP for DATETIME in SQL

phpmysqlisqldatatypestype-conversion

提问by ???

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?

我有一个 PHP 论坛,它采用的日期形式为 dd/mm/yyyy hh:mm:ss。但是,我需要将其作为 DATETIME 以yyyy-mm-dd hh:mm:ss. 如何转换这些数据?

回答by kodeart

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

您的日期时间格式错误:dd/mm/yyyy hh:mm:ss. 可能你的意思是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:

如果您有 5.3+ 版本,则可以安全地将日期时间转换为另一种格式。下面是一个例子:

$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.

小心以前的建议。有些是完全错误的,有些则可能导致错误。

回答by jjaybrown98

You can use the strtotime and date to rework the format.

您可以使用 strtotime 和 date 来修改格式。

$new_date = date( "Y-m-d H:i:s", strtotime( $old_date ) );

What this does is take your old date (dd/mm/yyyy hh:mm:ss), converts it to a unix timestamp that can then be used with the php date function to format the date to the desired format.

这样做是将您的旧日期 ( dd/mm/yyyy hh:mm:ss) 转换为 unix 时间戳,然后可以与 php date 函数一起使用将日期格式化为所需的格式。

回答by jugnu

if you have datetime avaialable from a from like above format then u just need to use following function.

如果您可以从上面的格式中获得日期时间,那么您只需要使用以下功能。

function localToMysql($dateTime){
  $date_chunks = explode('/', $dateTime);
    $time_chunks = explode(' ', $date_chunks[2]);
    $final_format = $time_chunks[0] . "-" . $date_chunks[1] . "-" . $date_chunks[0] . " " . $time_chunks[1];

return $final_format; }

返回 $final_format; }

回答by Jeshurun

Two of several possible ways:

几种可能的方法中的两种:

  1. Convert in code and then pass the converted value to mysql: $mysqldate = date( 'Y-m-d H:i:s', $phpdate );
  2. Let mysql do the work by using its built-in functions: $query = "UPDATE table SET datetimefield = FROM_UNIXTIME($phpdate) ...";
  1. 在代码中进行转换,然后将转换后的值传递给mysql: $mysqldate = date( 'Y-m-d H:i:s', $phpdate );
  2. 让 mysql 使用其内置函数来完成这项工作: $query = "UPDATE table SET datetimefield = FROM_UNIXTIME($phpdate) ...";