我的数据库中存储了两个包含以下数据的变量:
$date_published = 2012-05-04 00:00:00; //Straight from DB datetime field
$advert_duration = 15;
我希望自发布之日起15天内展示广告。为此,我需要计算时差。
我已经在网上阅读了有关计算时差的各个地方,并提出了以下代码
在我尝试计算方程式时,我似乎无法计算$ now之间的差异 - 今天的日期,$ date_published和$ advert_duration。我无法得到正确的结果:
function days_left($date_published, $advert_duration){
$date = new DateTime($date_published);
$now = new DateTime();
$days_elapsed = $date->diff($now)->format("%d");
$days_left = $advert_duration - $days_elapsed;
return $days_left;
}
答案 0 :(得分:2)
function getDaysLeft( $date, $duration )
{
// create $date and modify it by $duration
$date = new DateTime( $date );
$date->modify( sprintf( '+%d days', $duration ) );
// calculate the difference
$now = new DateTime();
$daysElapsed = (int) $now->diff( $date )->format( '%a' );
// set to negative value, if modified $date is before $now
if( $date < $now )
{
$daysElapsed = $daysElapsed * -1;
}
return $daysElapsed;
}
var_dump(
getDaysLeft( '2012-05-04 00:00:00', 15 ),
getDaysLeft( '2012-07-04 00:00:00', 15 )
);
答案 1 :(得分:1)
如果您要从数据库中提取广告,只需使用date function来计算:
WHERE DATE_SUB(CURDATE(),INTERVAL 15 DAY) >= date
或者您可以在PHP中执行此操作(您将获得UNIX时间戳):
$date = strtotime('+15 days', strtotime($date_published));