[英]PHP: making filter by today/yesterday
我在这里有一个过滤器:
$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。我想我只做time()-(3600 * 24)做错了。我该怎么办?
无需在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更易于使用,因此您不必费劲:)
您可能会收到错误消息,因为昨天我们有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更容易做到这一点。
time()将基于当前的第二个时间戳记,在此您需要当前/前几天的开始时间。 我建议使用mktime代替,php站点上有很多示例。
$today = date('Y-m-d',time());
$yesterday = date('Y-m-d',time() - 3600);
$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;
我想你想要这个。 希望我能帮助你...
//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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.