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

查看:41
本文介绍了将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天全站免登陆