在mysql中选择查询时如何显示正确的时间戳?

时间:2017-05-26 07:20:30

标签: php mysql symfony

我想显示查询的正确时间戳。我的数据库中的日期是这一天,日期时间戳是在欧洲/柏林中设置的。那是在我的服务器设置中,我总是得到这个结果。

  

2017-05-26 09:05:58

我想从查询中显示日期。这是我的查询代码

select logs.action_date_time from AuditLogs

如何在菲律宾转换logs.action_date_time日期?我应该看到这个结果

  

2017-05-26T09:05:58 + 02:00

我在google中搜索unix_timestamp,但是在查询之前我没有看到他们在select中使用的任何样本。我为此使用了symfony。我只是总结一下上面示例代码的结果。

const SELECT =
        'SELECT logs.id, logs.object_id AS objectId, logs.object_type AS objectType, logs.object_name AS objectName, '.'logs.action, logs.action_date_time AS actionDateTime, logs.action_status AS actionStatus, logs.subject, logs.user, '.'logs.description, logs.ip, logs.param03_value AS userId, logs.param04_value AS userDisplayName ';

    public function getNext($params)
    {
        // Hardcode for now
        $limit = $params['limit'] ? (int) $params['limit'] : self::DEFAULT_LIMIT;
        $limit++;

        $select = self::SELECT;
        $whereClause = $this->constructWhereClause($params);

        $sql = "
            $select FROM spoke.audit_logs AS logs
            $whereClause
            ORDER BY logs.action_date_time DESC, logs.id DESC
            LIMIT $limit";

        if ($params['cursor']) {
            $now = new \DateTime();
            $datetime = $now->getTimestamp();
            if (isset($params['datetime'])) {
                $datetime = $params['datetime'];
            }
            $whereClause = $this->constructWhereClause($params, 'logs1', false);
            $sql = "
                $select
                FROM spoke.audit_logs logs1, spoke.audit_logs logs
                WHERE logs1.id = logs.id 
                    $whereClause
                    AND logs1.action_date_time <= '$datetime'
                    AND (logs1.id < {$params['cursor']} OR logs1.action_date_time < '$datetime')
                ORDER BY logs1.action_date_time DESC, logs1.id DESC
                LIMIT $limit";
        }
        $stmt = $this->getEntityManager()->getConnection()->query($sql);

        return $stmt->fetchAll(\PDO::FETCH_ASSOC);

    }

2 个答案:

答案 0 :(得分:1)

您需要使用MySQL的CONVERT_TZ函数来转换时区,例如:

SELECT CONVERT_TZ(action_date_time, 'CEST', 'PHT') FROM AuditLogs;

或者,您也可以提供时区差异,例如:

SELECT CONVERT_TZ(action_date_time,'+01:00','+08:00') FROM AuditLogs;

Here's文档。

答案 1 :(得分:1)

将UTC日期时间列作为UNIX时间戳

SELECT UNIX_TIMESTAMP(CONVERT_TZ(`utc_datetime`, '+00:00', @@session.time_zone)) FROM `table_name`

来源在这里:Link