在PHP中格式化日期并存储在mysql中

时间:2017-07-26 18:29:19

标签: php mysql

我有这个语句在mysql中保存一个日期,但我想保存为例子:

September 24, 2011, 6:39 am

或者我应该拥有它,当我检索它时,我就这样回应它?

try {
      $date = date('Y-m-d H:i:s');
        //insert into database with a prepared statement
        $stmt = $db->prepare('INSERT INTO admin (username, password, email, register_date, active) VALUES (:username, :password, :email, :register_date, :active)');
        $stmt->execute(array(
            ':username' => $_POST['username'],
            ':password' => $hashedpassword,
            ':email' => $_POST['email'],
            ':register_date' => $date,
            ':active' => $activasion
    ));
//else catch the exception and show the error.
        } catch(PDOException $e) {
            $error[] = $e->getMessage();
        }

2 个答案:

答案 0 :(得分:0)

<?php
/* 
   * F --> for full month
   * D -->day
   * Y --> Year
   * H -->Hour
   * m -->minute
   * A -- PM or AM

*/
$date = date("F d, Y, H:m A");
echo $date;   
?>

输出

July 26, 2017, 21:07 PM

答案 1 :(得分:0)

// original datetime string:
$str = 'September 24, 2011, 6:39 am';

$stmt->execute(array(
        ':username' => $_POST['username'],
        ':password' => $hashedpassword,
        ':email' => $_POST['email'],
        ':register_date' => strftime("%Y-%m-%d %H:%M:%S", strtotime($str)),
        ':active' => $activasion
));

日期格式为:2011-09-24 06:39:00,MySQL会很高兴。

Live demo

文档:strftime | strtotime