将用户输入的日期字符串存储为datetime

时间:2011-01-25 09:21:50

标签: php mysql

我正在使用php,需要解析格式为dd/mm/yyyy的日期字符串并将其存储在MySql中。
如何将字符串转换为MySql表中的日期时间变量?

2 个答案:

答案 0 :(得分:1)

可能最好的方法是使用它:http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date

SELECT STR_TO_DATE('04/31/2004', '%m/%d/%Y');
-> '2004-04-31'

或等效的PHP函数,如: http://www.php.net/manual/en/function.date-parse-from-format.php(来自PHP 5.3)

通用PHP函数看起来像

function convertDate($dateString) {
  return date('Y-m-d H:i:s',strtotime(str_replace('/','-',$dateString)));
}

function convertDate($dateString) {
  $a = explode($dateString('/'));
  return "{$a[2]}-{$a[1]}-{$a[0]} 00:00:00";
}

答案 1 :(得分:0)

首先,您应该存储所需格式日期的配置,可能是这样的: 知道ISO_DATE FORMAT是“Y-m-d” 您必须以某种方式保存输出配置,至少是分隔符。 如果您知道分隔符并且您知道输入日期的格式,则可以使用checkdate()对其进行验证,并通过按预定义分隔符展开值将其转换为ISO标准。

我有一个验证对象,告诉我某个字段是否属于某种类型(String,Date,Datetime,Integer,Float),然后格式化发送给SQL的参数: 例如,假设我将这个数组从我的html表单转换为PHP:

$_POST["DATA"] = array("name"=>"Koko bongo","age"=>12,"graduation_date"=>"12/06/1986");

我们定义了一个验证数组,如下所示:

$validator= array("name"=>"string","age"=>"integer","graduation_date"=>"date");

我为每个表配置了一个自动化的配置,但您可以通过使用像这样工作的evalAndFormatType函数来定制地实现它

function evalAndFormatType($value,$type) {

switch strtolower($type) {


     case "integer":

         $item = is_numeric($value) && !strstr($value,DECIMAL_SEPARATOR) ? intval($item) :false;

     break;
     case "Date":/*we suppose that somehow we now the order, how you do it it is your decision: configuration array,constants etc*/
         $check = explode(DATE_SEPARATOR,$value);
         $item = sizeof($check) == 3 && checkdate(intval($check[1]),intval($check[0]),intval($check[2])) ? $check[2]."-".$check[1]."-".$check[0] : false;
     break;
     default:
       throw Exception("Unknown type ".$type);
     break;

}

  return $item;
}

now, in your code you can say


$_DATA = $_POST["DATA"]; // the previously defined array

$errMsg = array();

foreach($_DATA as $k=>$v) {
   $_DATA[$k] = evalAndFormat($v,$validator[$k]);

   if($_DATA[$k] === false) {

        $errMsg[$k] = "requires type ".$validator[$k];

   }

}

if(empty($errMsg)){

    $sql= ....WHATEVER USING THE INFO

} else {

  return $errMsg;


/*this can be used to show errors nicely near your text boxes by parsing the expected keys or sending it by JSON etc
or
you could create a string out of it by using locale data that you might have which could output something like
Required fields: Graduation date[invalid type],Name,Age ... etc
"/

我希望这能回答你的问题并解释我的“奇怪”方法。

}