MySql& PHP - 如何将字符串转换为DATETIME [英] MySql & PHP - How to convert a string to DATETIME

查看:266
本文介绍了MySql& PHP - 如何将字符串转换为DATETIME的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数据(由用户隔离),如:


  1. 10-12-2010

  2. XX-12-2010

  3. 10-XX-2010

  4. 10-12-XXXX

(请注意,我添加XX(或XXXX)当数据不被覆盖时。)



如何使用MySql语法将这些字符串转换为 DATETIME



感谢



更新

  $ day =(is_numeric($ _ POST ['day'])&&$ _POST ['day']> 0&& $ _POST [' ']< 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 )+1))? $ _POST ['year']:'0000';
$ data = $ year。 - 。$ month。 - 。$ day;
$ mysqlDate = date('Y-m-d',strtotime($ data));
echo $ mysqlDate;

有一个问题:如果数据是*空 - 12-2010它打印 2010 -11-30 为什么?

解决方案

如果你确定你不想要要求所有的日期字段,只要它们不存在就将其填充为零,如下所示:

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

否则,如果您不担心空白日期,但不担心非标准输入,可以执行以下操作:

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






code> $ date = date('Ymd G:i:s',strtotime($ _ POST ['dataThatUserEntered']));



只需确保您验证用户输入,否则您可能会发现 $ date ='1970-01-01 00:00:00 如果他们进入疯狂的东西。


I have some data (insered by users) like :

  1. 10-12-2010
  2. XX-12-2010
  3. 10-XX-2010
  4. 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.

这篇关于MySql&amp; PHP - 如何将字符串转换为DATETIME的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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