[英]Find if date is less than 7 days from now
How can i find out if expiry date is less than 7 days from now? 我怎样才能知道到期日期从现在起不到7天?
The expiry date format looks like this: 2016-04-13 到期日期格式如下: 2016-04-13
I have a code here, but it doesn't work: 我在这里有一个代码,但是不起作用:
if($record->$c < date('Y-m-d', strtotime('-7 day'))){
// this is true
}
Hope anyone could help me. 希望有人能帮助我。
Just convert both units to unix timestamp, make your subtraction, then divide it by 86400: 只需将两个单位都转换为unix时间戳,进行减法,然后将其除以86400:
$expiry_date = '2016-04-18';
$today = time();
$interval = strtotime($expiry_date) - $today;
$days = floor($interval / 86400); // 1 day
if($days < 7) {
echo 'less';
}
Or another way with DateTime
classes: 或使用
DateTime
类的另一种方法:
$expiry_date = '2016-04-18';
$expiry_date = new DateTime($expiry_date);
$today = new DateTime();
$interval = $today->diff($expiry_date);
$day = $interval->format('%r%a');
if($day < 7) {
echo 'less';
}
Example conditions: 条件示例:
$expiry_date = '2016-04-18';
$today = time();
$interval = strtotime($expiry_date) - $today;
$day = floor($interval / 86400); // 1 day
if($day >= 1 && $day < 7) {
echo 'between 1 - 7 days';
} elseif($day <= 0) {
echo 'deadline';
} else {
echo 'soon';
}
Just change / tweak it depending on what you're trying to do. 只需根据您要执行的操作进行更改/调整即可。
Recommend exploring date_diff()
function: 推荐探索
date_diff()
函数:
http://php.net/manual/en/function.date-diff.php http://php.net/manual/zh/function.date-diff.php
My challenge was different: 我的挑战与众不同:
// Count days is date range
function count_days_in_range($date1, $date2) {
$date1 = date_create($date1);
$date2 = date_create($date2);
$interval = date_diff($date1, $date2);
$days = $interval->days;
return $days;
}
But this function will make your life much easier. 但是此功能将使您的生活更加轻松。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.