【问题标题】:Problems getting the amount of rows in a table, where the date is > value获取表中行数的问题,其中日期>值
【发布时间】:2015-01-12 20:18:21
【问题描述】:

我要做的唯一事情是显示自用户上次访问他的统计信息仪表板以来的新交易量,我以为我很好地理解了这个概念,但似乎我遇到了一个问题。

这个问题是用户拥有的current-date和SQL使用的current-timestamp不是一回事。 (我会假设这会因时区而异?)

我想我正在寻找的是什么 time=zone MySQL 存储 DATETIME(当前时间戳)字段,所以我可以获得用户的当前时间戳,他的时区,并尝试执行逻辑使它们相同。

或者有没有更简单的方法来解决这个问题?我目前在仪表板中使用 DATETIME 格式来显示购买日期的信息,其格式类似于 2015-01-12 01:02:18 在表格内。

也许我的查询是错误的,谁知道:

function getNewTransactions($connection, $user) {
    $statement = $connection->prepare("SELECT `lastcheck` FROM `login` WHERE 1");
    $statement->execute();
    while($row = $statement->fetch()) {
        $d = $row['lastcheck'];
    }

    $statement = $connection->prepare("SELECT * FROM `transactions` WHERE `date` > :d");
    $statement->bindParam(":d", $d);
    $statement->execute();

    $transactions = 0;
    while($row = $statement->fetch()) {
        $transactions++;
    }

    $date = date("Y-m-d H:i:s");
    $statement = $connection->prepare("UPDATE `login` SET `lastcheck` = '{$date}' WHERE `username`=:name");
    $statement->bindParam(":name", $user);
    $statement->execute();

    return $transactions;
}

如果我将 > 换成

【问题讨论】:

    标签: php mysql date datetime


    【解决方案1】:

    http://php.net/manual/en/function.date-default-timezone-set.php

    这应该可以帮助您设置时区。

    【讨论】:

    • 这应该在设置日期之前定义。
    • 如果我知道 SQL Server 的时区,这将起作用,但考虑到这将是一个分布式产品,它必须是动态的。并非所有服务器都位于同一位置。
    【解决方案2】:

    您可以使用

    从 MySql 获取时区
      SELECT @@system_time_zone;
    

    或从 GMT 获取 +/- 偏移量

      SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP);
    

    在你的情况下,你可以尝试这样的事情

      SELECT convert_tz(`lastcheck`, 'TIMEZONE_LASTCHECK_IS_STORED_IN', @@system_time_zone,  ) as lastcheck 
      FROM `login` 
      WHERE 1
    

    但理想情况下,数据库中的所有日期时间都应该存储在同一个时区中。那将消除您当前的问题。你可以通过 ...

       SELECT @@system_time_zone 
       ... and save the value into the PHP variable $db_timezone_code
    
       ... then replace the $date assignment with ...       
       $db_timezone = new DateTimeZone($db_timezone_code);
       $now         = new DateTime('now');
       $now->setTimeZone($db_timezone);
       $date        = $now->format('Y-m-d H:i:s');
       ... $date is now converted from the PHP servers timezone
       ... to the databases default timezone.  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多