这里我在数据库中存储了两个日期,比如开始日期为2014-07-07 00:00:00,结束日期为2014-07.15 23:59:59。现在我该如何检查这两天之间的当前日期
$date1 = '2014-07-07 00:00:00';
$date2 = '2014-07-15 23:59:59';
$now = new DateTime();
$current_time = $now->format('Y-m-d H:i:s');?>
如果从数据库中检索date1和date2,并将其与从服务器中获取的当前日期进行比较,如果日期在这两天之间,则应该显示从现在起的结束时间。
用途:
$date1 = '2014-07-07 00:00:00';
$date2 = '2014-07-15 23:59:59';
$cdate1 = new DateTime($date1);
$vdate1 = $cdate1->getTimestamp();
$cdate2 = new DateTime($date2);
$vdate2 = $cdate1->getTimestamp();
比较整数($vdate1和$vdate2(
结果将以秒为单位
享受:(
作为面向对象风格的替代方案,您可以将对象创建为DateTime类的实例,例如:
$date1 = new DateTime('2014-07-07 00:00:00');
$date2 = new DateTime('2014-07-15 23:59:59');
$now = new DateTime();
然后,按照你的逻辑,你可以比较now
是在其他日期之前还是之后,比如:
var_dump($date2 > $now);
或者,您可以使用检索DateInterval接口的实例
$now_interval_from_date1 = $date1->diff($now);
然后使用CCD_ 2方法来精确地知道时间/天等。。差异,如:
$now_interval_from_date1->format("%R%H hours")
您可以在此处找到格式参数:http://www.php.net/manual/it/dateinterval.format.php
如果两个日期的格式完全相同,php允许字符串比较。
因此,您可以执行以下操作:
if(strcmp($date1, $current_time) <= 0 and strcmp($date2, $current_time) > 0)
{
// The date is within the limits
}
strcmp
是字符串比较的一个更安全的函数
因此,在您的情况下,您可以有以下内容:
<?php
$con=mysqli_connect("localhost","root","","proms"); // Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
date_default_timezone_set("America/New_York");
$current_time =date("h:i:sa");
$result = mysqli_query($con,"SELECT * FROM image");
while($row = mysqli_fetch_array($result)) {
if(strcmp($row['start_date'],$current_time) <= 0 && strcmp($row['end_date'],$current_time) > 0) {
// The date is within the limits
echo "yes";
}
}
?>
'start_date'
和'end_date'
应替换为字段的名称。
您可以执行以下操作来比较两个日期之间的当前时间
$date1 = '2014-07-07 00:00:00';
$date2 = '2014-07-15 23:59:59';
$now = date('Y-m-d H:i:s');
$date1TimeStamp = strtotime($date1);
$date2TimeStamp = strtotime($date2);
$nowTimeStamp = strtotime($now);
if($date1TimeStamp <= $nowTimeStamp || $date2TimeStamp >= $nowTimeStamp){
$seconds_diff = $date2TimeStamp - $nowTimeStamp;
$days = $seconds_diff/(3600*24);
}else
echo 'No, out';
编辑计算,现在显示从现在到结束日期的剩余天数
if(strtotime('now') > strtotime($date1) && strtotime('now') < strtotime($date2)) {
$diff = strtotime($date2) - strtotime('now');
}
$diff
则包含以毫秒为单位的两个日期之间的差异。只需将毫秒转换为天:小时:分钟(数学?(