我正在开发一个php应用程序。我已经为应用程序生成了类似许可证这样的访问代码,通常从installation.When的日期起一年-- DB中设置的到期日期--或者即将到达,它应该给出消息。最后一天到期后,应该重定向到许可页面。现在的问题是:当它过期的时候,它仍然有一些日子要过期。也许我的代码是错的,或者我选择的方式是错误的。有人能帮忙吗。
<?php
$se = "SELECT * FROM license WHERE status=1 ORDER BY endDate DESC";
$conf = mysqli_query($connection,$se);
$row = mysqli_fetch_array($conf);
$tday = new DateTime(date("Y-m-d"));
$eday = new DateTime($row['endDate']);
$interval =$eday->diff($tday);
$diff =$interval->format("%a");
$mth=$interval->m;
$days =$interval->d;
if($diff<=90){
print '<script type="text/javascript">';
print 'alert("License has expired.Contact me for renewal: developer@yahoo.com or Technical Support: mobileNo")';
print '</script>';
}else if($diff<=45){
print '<script type="text/javascript">';
print 'alert("License has expired.Contact me for renewal: developer@yahoo.com or Technical Support: mobileNo")';
print '</script>';
}else if($diff<=0){
print '<script type="text/javascript">';
print 'alert("License has expired.Contact me for renewal: developer@yahoo.com or Technical Support: mobileNo")';
print '</script>';
echo "<script> document.location='License.php';</script>";
}
?>请参阅DB记录:

发布于 2016-05-20 09:05:18
首先,在格式化间隔时,应该添加%R:它将前缀格式为+或-,这样就可以与零进行比较(对于负值而言):
$dif = $interval->format('%R%a');第二,您总是显示相同的消息。你不能按正确的顺序进行比较。你应该这样比较:
switch (true) {
case ($diff <= 0):
// Expired, need renewal
break;
case ($diff <= 45):
// Expires within the next 45 days
break;
case ($diff <= 90):
// Expires within the next 90 days
break;
}如果愿意,可以使用if/elseif/else语句。但秩序很重要。这个信息也很重要:)
更新
您需要计算正确的差异:
$interval = $tday->diff($eday);将其视为:
$interval = $date_from->diff($date_to);因此,如果$date_to大于$date_from,则间隔将为正($date_to为+$interval days)。
当$date_to出现在$date_from之前时,间隔将为负值($date_to为-$interval days,这意味着$date_to在几天前为$interval )。
因此,在您的例子中,如果$interval是肯定的,那么许可证将在$interval天到期。否则,许可证将在$interval日过期。
发布于 2016-05-20 09:46:03
使用下面的代码。
试着用strtotime()。
$date1 = "2016-05-07";
$date2 = "2016-05-06";
$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
echo $days . "days";输出
1 days发布于 2016-05-20 12:14:11
谢谢大家。你的建议对me.All有帮助,我应该说:
<?php
if($today>$db_expiry_date){
redirect_to(license.php)
}else{
contine.....
}
?>此外,您还可以使用以下方法来处理剩下的天数:
<?php
if($diff<=45 && $today<$db_expiry_date){
echo 'License will expire with next 45days';
}elseif($diff<=90 && $today<$db_expiry_date){
echo 'License will expire with next 90days';
}else if($today>$db_expiry_date){
echo 'License Expired';
redirect_to('License.php');
}
}
?>https://stackoverflow.com/questions/37342254
复制相似问题