设置PHP日期时间格式

时间:2014-11-16 05:20:00

标签: php mysql datetime

我在MySQL表中有一个类型为' datetime'的列。 如何从PHP获取当前日期和时间格式的值 - 例如:" 2014-11-09 15:06:51"并设置为变量?

感谢。

3 个答案:

答案 0 :(得分:0)

检查此PHP documentation以获得更多说明。

$DateTime = date('Y-m-d H:i:s');

Ref

答案 1 :(得分:0)

您可以使用MySql的CURDATE()。不需要使用php。

INSERT INTO  `db`.`data1` (
`id` ,
`date`
)
VALUES (
'2', CURDATE()
)

有关详情,请参阅http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_curdate

答案 2 :(得分:0)

如果你在课堂上这样做,你可以使用我的DateTime getter和setter。假设$this->Date是一个php DateTime object,而你正在使用带有DATETIME列的mysql。

以下是使用它的内容:

$this->setDate($whatever_date); // give it a timestamp, mysql DATETIME, or anything that can be read by strtotime()

// Need to put the date into mysql? Use this:
$this->getDate('mysql');

// Need to get the date so a person can read it? 
$this->getDate('human');

// want it as a timestamp?
$this->getDate('unix');

以下是方法:

// accepts 'human', 'mysql', 'unix', or custom date() string
function getDate($format='human'){

    if(get_class($this->Date)!='DateTime') return FALSE;


    try{

        switch ($format) {
            case 'human':
                return $this->Date->format('M j, Y g:i a'); // Show date and time
                // return $this->Date->format('M j, Y'); // Just the date
                break;

            case 'mysql':
                return $this->Date->format('Y-m-d H:i:s');
                break;

            case 'unix':
                return $this->Date->format('U'); // may return a negative number for old dates
                break;

            default:
                return $this->Date->format($format);
                break;
        }

    } catch (Exception $e){
        throw new Exception('Can not use that format for getting DateTime');
        return FALSE;
    }
}

// Sets as a DateTime object - accepts either a timestamp or a date() string
function setDate($date){
    try{

        if(is_numeric($date) && (int)$date==$date){ // timestamp
            $this->Date = new DateTime(date('F j, Y, g:i a', $date));
        } else {
            $this->Date = new DateTime($date);
        }


    } catch (Exception $e){
        throw new Exception('Can not set the given value ('.$date.') as DateTime');
        return FALSE;
    }
    return TRUE;
}

如果你没有使用类,你可能希望将它们组合成一个采用你所拥有的格式的函数,并返回你需要的格式。

相关问题