2010-11-01 130 views
1

我这里有一个过滤器:PHP:让今天的过滤器/昨天

$today = time() - (3600*24); 
$Yday = time() - (3600*48); 


$getMsgsToday = mysql_query("SELECT * FROM users_msgs WHERE uID = '$USER' AND date > $today ORDER by date DESC LIMIT 10"); 


$getMsgsYday = mysql_query("SELECT * FROM users_msgs WHERE uID = '$USER' AND date BETWEEN $Yday AND $today ORDER by date DESC LIMIT 10"); 

这并不正常工作。如果时间为01:00,则会在昨天的“今日”日期(例如23:00,22:00和21:00)中显示您,并且将在第一天的01:00之后在“昨天” 。

我该如何解决这个问题,以便与时间正确?所以00:01是今天和23:59是昨天..我认为我做错了只是做时间() - (3600 * 24)..我应该怎么做?

回答

3

你可能会得到错误,因为我们昨天DST 。使用下面的代码,这是考虑到的。你不应该自己计算时间戳。这很容易出错。

$now  = time();     // gives timestamp of right now 
$today  = strtotime('today')  // gives timestamp of today 00:00 
$yesterday = strtotime('yesterday'); // gives timestamp for yesterday 00:00 
$ts24hago = strtotime('-24 hours'); // gives timestamp 24 hours ago 

而且我同意El Yobo的说法,从MySql中很容易做到这一点。

0

time()将基于当前的第二个时间戳,您需要当前/前一天的开始时间。我建议使用mktime代替,在php网站上有很多例子。

0
$today = date('Y-m-d',time()); 
$yesterday = date('Y-m-d',time() - 3600); 
+0

这并不影响我以前的产品 – Johnson 2010-11-01 01:18:49

-1
$today_start = strtotime(date('Y-m-d 00:00:00')); 
$today_end = strtotime(date('Y-m-d 23:23:59')); 
$yesterday_end = $today_start - 1; 
$yesterday_start = $yesterday_end - 86399; 
3

没有必要计算这个东西在PHP,这样做在SQL本身。

-- Today's messages: round the "date" field to be only a date, not a timestamp, then compare 
$getMsgsToday = mysql_query("SELECT * FROM users_msgs WHERE uID = '$USER' AND cast(`date` as date) = cast(now() as date) ORDER by date DESC LIMIT 10"); 

-- Yesterday's messages: round the "date" field to be only a date, then compare to today - 1 day 
$getMsgsYday = mysql_query("SELECT * FROM users_msgs WHERE uID = '$USER' AND cast(`date` as date) = date_sub(cast(now() as date), interval 1 day) ORDER by date DESC LIMIT 10"); 

在大多数数据库中的日期操作功能更容易比PHP使用的,所以你不必使您的生活困难:)

+0

您好。谢谢你的回答,但我需要用时间戳做到这一点。 – Johnson 2010-11-01 01:16:55

0

我想你想这个。希望我能帮到你.....

//Date format(YYYY-MM-DD) change to timestamp 
function getTS($date){ 
    if (false ===preg_match('/\d{4}-\d{2}-\d{2}/i', $date)) 
     return 0; 
    list($year,$month,$day) = explode('-',$date); 
    return mktime(0,0,0,$month,$day,$year); 
} 
//Get Today and Yesterday Timestamp. 
$today = getTS(date('Y-m-d')); 
$Yday = getTS(date('Y-m-d',strtotime('yesterday'))); 

应用sql脚本。

$getMsgsToday = mysql_query("SELECT * FROM users_msgs WHERE uID = '{$USER}' AND date > {$today} ORDER by date DESC LIMIT 10"); 

$getMsgsYday = mysql_query("SELECT * FROM users_msgs WHERE uID = '{$USER}' AND date BETWEEN {$Yday} AND {$today} ORDER by date DESC LIMIT 10"); 
相关问题