将php日期转换为mysql格式 [英] convert php date to mysql format

查看:57
本文介绍了将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

这篇关于将php日期转换为mysql格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆