日期字符串不会转换为时间戳

时间:2013-06-27 20:41:02

标签: php postgresql timestamp string-conversion

我想抓住今天ctime的任何记录。对于某些原因,& tomorrow和&昨天没有任何价值。如果我删除strtotime(),则其值是从mktime派生的日期的字符串表示。我对strtotime做错了什么?

PHP:

public function fetchToday()
{
    $tomorrow  = strtotime(mktime(0, 0, 0, date("m")  , date("d")+1, date("Y")));
    $yesterday  = strtotime(mktime(0, 0, 0, date("m")  , date("d")-1, date("Y")));      
    $q = "SELECT * FROM $this->_table WHERE ctime < $tomorrow AND ctime > $yesterday";      
    return $this->fetchBySelect($q);
}

错误:

ModelFactory - 'ERROR: syntax error at or near "AND" LINE 1: SELECT * FROM motd WHERE ctime < AND ctime >

PostrgeSQL表格字段:

ctime timestamp(0) with time zone

查询:

SELECT * FROM motd WHERE ctime < 1372402800 AND ctime > 1372230000;

`

5 个答案:

答案 0 :(得分:3)

为什么不呢:

$tomorrow  = date("Y-m-d", strtotime("+1 day")); // sets tomorrow = 2013-06-28
$yesterday  = date("Y-m-d", strtotime("-1 day")); // sets tomorrow = 2013-06-26

这是假设您的ctime列是MySQL日期戳。如果它是unix时间戳,那么:

$tomorrow  = strtotime("+1 day");
$yesterday  = strtotime("-1 day");

由于strtotime将param转换为unix时间戳。使用strtotime和mktime,你的代码是多余的。

编辑:根据以前的帖子,看起来你的ctime列是一个unix时间戳,所以我的第二个例子是要走的路。 strtotime("+1 day")将返回一个表示NOW + 1日的unix时间戳的int,并返回-1 Day的反转。

答案 1 :(得分:3)

到目前为止,所有答案都集中在php方面,但另一方面,我会说正确的解决方案是使用PostgreSQL功能,并将php代码更改为:

public function fetchToday()
{
    $q = "SELECT * FROM $this->_table WHERE ctime < 'tomorrow'::timestamptz AND ctime > 'yesterday'::timestamptz;";      
    return $this->fetchBySelect($q);
}

答案 2 :(得分:2)

strtotime的返回值上使用mktime毫无意义。这两个函数都返回一个Unix时间戳,因此请使用其中一个。我建议使用strtotime,因为它使用起来很简单:

$tomorrow  = strtotime('tomorrow');
$yesterday = strtotime('yesterday');

其中每个都会返回对应于当天开始前午夜的时间戳,这看起来就像你想要的那样。

答案 3 :(得分:1)

我认为这些语句中存在错误,因此它们产生空字符串并使查询失败。

$tomorrow  = strtotime(mktime(0, 0, 0, date("m")  , date("d")+1, date("Y")));
$yesterday  = strtotime(mktime(0, 0, 0, date("m")  , date("d")-1, date("Y")));      

mktime()返回unix时间戳,你不需要使用strtime()。

这取决于您在数据库中存储数据的方式。如果将它们保存为TIMESTAMP,则只需省略strtotime。

如果您将它们保留为ISO“YYYY-MM-DD”,则仅使用日期()。

答案 4 :(得分:1)

public function fetchToday()
{
    $tomorrow = strtotime("+1 day", strtotime(date("Y-m-d H:i:s"))); 
    $yesterday= strtotime("-1 day", strtotime(date("Y-m-d H:i:s"))); 
    $q = "SELECT * FROM ".$this->_table." WHERE ctime < ".$tomorrow." AND ctime > ".$yesterday;      
    return $this->fetchBySelect($q);
}
相关问题