mysql把空字符串转成datetime,MySql& PHP - 如何将字符串转换为DATETIME

I have some data (insered by users) like :

10-12-2010

XX-12-2010

10-XX-2010

10-12-XXXX

(Notice that I add XX (or XXXX) when the data is not insered.)

How can I convert these String to DATETIME by using MySql syntax?

Thanks

UPDATE

$day=(is_numeric($_POST['day']) && $_POST['day'] > 0 && $_POST['day'] < 32) ? $_POST['day'] : '00';

$month=(is_numeric($_POST['month']) && $_POST['month'] > 0 && $_POST['month'] < 13) ? $_POST['month'] : '00';

$year=(is_numeric($_POST['year']) && $_POST['year'] > 1999 && $_POST['year'] < (date("Y")+1)) ? $_POST['year'] : '0000';

$data=$year."-".$month."-".$day;

$mysqlDate=date('Y-m-d', strtotime($data));

echo $mysqlDate;

There is a problem : if data is *empty-12-2010" it print 2010-11-30. Why?

解决方案

If you're sure you don't want to require all the date fields, just fill them with zero if they don't exist, like this:

$month = ($_POST['month'] == '') ? '00' : $_POST['month'];

otherwise, if you're worried not about blank dates, but about non-standard input, you could do:

$month = (is_numeric($_POST['month']) && $_POST['month'] > 0 && $_POST['month'] < 13) ? $_POST['month'] : '00'

$date = date('Y-m-d G:i:s', strtotime($_POST['dataThatUserEntered']));

should do the trick, no?

Just make sure you validate the user input, otherwise you may find that $date = '1970-01-01 00:00:00 if they enter something crazy.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值