我在这里有一个过滤器:
$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)..我该怎么办?
答案 0 :(得分: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更容易使用,因此您不必为生活带来困难:)
答案 1 :(得分: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中更容易做到这一点。
答案 2 :(得分:0)
time()将基于当前到第二个时间戳,您需要当前/前几天的开头。我建议使用mktime代替,php网站上有很多例子。
答案 3 :(得分:0)
$today = date('Y-m-d',time());
$yesterday = date('Y-m-d',time() - 3600);
答案 4 :(得分: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");
答案 5 :(得分:-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;