如何将 php 中的日期转换为 SQL 格式?(并插入)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4791203/
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-25 14:22:54  来源:igfitidea点击:

How can i convert a date in php to SQL format ? (and insert it)

phpsqldatetime

提问by Yochai Timmer

I'm trying to insert a date , lets say CURDATE()to an sql DateTimefield.

我正在尝试插入一个日期,让我们说CURDATE()一个 sqlDateTime字段。

My date is in the format of: 28/01/2008

我的日期格式为: 28/01/2008

When I try to insert it to the SQL, I get just zeroes.

当我尝试将它插入到 SQL 中时,我只得到零。

So how can I convert it properly?

那么我该如何正确转换呢?

回答by Dan Grossman

$newdate = date('Y-m-d', strtotime($olddate));

回答by Sarfraz

I'm trying to insert a date , lets say CURDATE() to an sql DateTimefield.

我正在尝试插入一个日期,让我们说 CURDATE() 到一个 sql DateTime字段。

$timestamp = strtotime($old_date);
$mydate = date('Y-m-d H:i:s', $timestamp);

回答by wimvds

Since you're using the European date notation (dd/mm/yyyy) the strtotimefunction will return 0 (which in turn will be converted to 1970-01-01 by date) if you don't use -or .as separator.

由于您使用欧洲日期表示法(DD / MM / YYYY)的的strtotime函数将返回0(这反过来将被转换为1970-01-01日期),如果你不使用-作为分隔符。

So if you want to use strtotime, then you will have to change your date strings just a bit :

因此,如果您想使用 strtotime,那么您将不得不稍微更改您的日期字符串:

$olddate = '28/01/2008';
$newdate = strtotime(str_replace('/', '-', $olddate));

$newdate should now contain '2008-01-28'...

$newdate 现在应该包含'2008-01-28'...

回答by MatTheCat

join('-',array_reverse(explode('/',$date)))

to get the standard YYYY-MM-DD Mysql date format.

获取标准的 YYYY-MM-DD Mysql 日期格式。

or just use MySQL' DATE_FORMAT

或者只使用 MySQL 的DATE_FORMAT

回答by RichardTheKiwi

I'm trying to insert a date , lets say CURDATE() to an sql DateTime field.

我正在尝试插入一个日期,让我们说 CURDATE() 到一个 sql DateTime 字段。

Why don't you use the MySQL function directly?

为什么不直接使用MySQL函数呢?

insert tbl (id, other, datecol)
values(NULL, 'abcdef', CURDATE());

My date is in the format of: 28/01/2008

我的日期格式为:28/01/2008

If it is not CURDATE() you want, but is a PHP variable in dd/mm/yyyy format instead, then see this MySQL man pagefor how to format the literals. Safe formats are YYYY-MM-DDand YYYYMMDDwithout time.

如果它不是您想要的 CURDATE(),而是 dd/mm/yyyy 格式的 PHP 变量,请参阅此MySQL 手册页了解如何格式化文字。安全格式YYYY-MM-DD,并YYYYMMDD没有时间。

$date = '28/01/2008';
$query = "insert tbl (id, other, datecol)
          values(NULL, 'abcdef', '" . date('Ymd', strtotime($date)) . "');";

Note: yyyymmdd is also a valid format in SQL Server.

注意:yyyymmdd 也是 SQL Server 中的有效格式。