将php日期转换为mysql格式

问题描述:

我在 php 中有一个使用此代码的日期字段:

I have a date field in php which is using this code:

$date = mysql_real_escape_string($_POST['intake_date']);

如何将其转换为 MySql 格式 0000-00-00 以包含在 db 中.是这样的:date('Ymd' strtotime($date);.我问的原因是因为我已经尝试了这个的变体,但我似乎无法让它工作.要么显示为 1970 或其他一些变体非常感谢

How do I convert this to MySql format 0000-00-00 for inclusion in db. Is it along the lines of: date('Y-m-d' strtotime($date);. The reason I ask, is because I have tried variations of this and I cannot seem to get it to work. Either displays as 1970 or some other variation of that. Many thanks

$date = mysql_real_escape_string($_POST['intake_date']);

1.如果您的 MySQL 列是 DATE 类型:

1. If your MySQL column is DATE type:

$date = date('Y-m-d', strtotime(str_replace('-', '/', $date)));

2.如果您的 MySQL 列是 DATETIME 类型:

2. If your MySQL column is DATETIME type:

$date = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date)));

您不必使用 strototime(),因为它不适用于破折号 - 分隔符,它会尝试进行减法运算.

You haven't got to work strototime(), because it will not work with dash - separators, it will try to do a subtraction.

更新,您的日期格式无法使用strtotime(),请改用此代码:

Update, the way your date is formatted you can't use strtotime(), use this code instead:

$date = '02/07/2009 00:07:00';
$date = preg_replace('#(\d{2})/(\d{2})/(\d{4})\s(.*)#', '$3-$2-$1 $4', $date);
echo $date;

输出:

2009-07-02 00:07:00