设置 PHP 日期时间格式

Posted

技术标签:

【中文标题】设置 PHP 日期时间格式【英文标题】:Setting PHP date time format 【发布时间】:2015-01-13 06:21:33 【问题描述】:

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

谢谢。

【问题讨论】:

NOW() function in PHP的可能重复 【参考方案1】:

查看PHP documentation 以获得更多说明。

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

Ref

【讨论】:

【参考方案2】:

你可以使用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

【讨论】:

【参考方案3】:

如果你在课堂上这样做,你可以使用我的 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;

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

【讨论】:

以上是关于设置 PHP 日期时间格式的主要内容,如果未能解决你的问题,请参考以下文章

如何设置wordpress主题的日期格式

php怎么将指定日期转换为时间戳

从日期选择器到 mysql/php 的奇怪日期格式

日期和时间(10)

PHP MySQL 日期差异

PHP语法笔记二