使用 PHP 将日期时间与当前时间进行比较
Comparing datetime to current time using PHP
鉴于 $some_date
等于 2015-02-12 10:28:04
,我如何使用 PHP(而不是 MySQL)?
strtotime
和DateTime
class是我们的朋友。其中 $x
是小时数:
if(($time = strtotime($some_date)) > $time + ($x * 360)) {
//do something its more than X hours
}
这可能无法跨越夏令时界限,所以也许:
if(($time = strtotime($some_date)) > strtotime("+$x hours", $time)) {
//do something its more than X hours
}
这将确定您的日期是否距当前日期时间不到 2 小时
<?php
$date = new DateTime(); //set current datetime to variable
$date->setTimezone(new DateTimeZone('America/Detroit')); //set timezone if you like
$fdate = $date->format('Y-m-d H:i:s'); //change format to year - month - day, hour, minute, seconds
$some_date = strtotime('2015-02-13 18:30:04'); // this is your datetime. use your time or change $some_date to your variable
$new_date = strtotime($fdate) - $some_date;
$minute_date = $new_date / 60; // convert to minutes
$hour_date = $minute_date / 60; // convert to hours
print $hour_date;
if($hour_date > 2){ // change the 2 to whatever you want it to be.
print "more than two hours";
}else{
print "less than two hours";
}
?>
鉴于 $some_date
等于 2015-02-12 10:28:04
,我如何使用 PHP(而不是 MySQL)?
strtotime
和DateTime
class是我们的朋友。其中 $x
是小时数:
if(($time = strtotime($some_date)) > $time + ($x * 360)) {
//do something its more than X hours
}
这可能无法跨越夏令时界限,所以也许:
if(($time = strtotime($some_date)) > strtotime("+$x hours", $time)) {
//do something its more than X hours
}
这将确定您的日期是否距当前日期时间不到 2 小时
<?php
$date = new DateTime(); //set current datetime to variable
$date->setTimezone(new DateTimeZone('America/Detroit')); //set timezone if you like
$fdate = $date->format('Y-m-d H:i:s'); //change format to year - month - day, hour, minute, seconds
$some_date = strtotime('2015-02-13 18:30:04'); // this is your datetime. use your time or change $some_date to your variable
$new_date = strtotime($fdate) - $some_date;
$minute_date = $new_date / 60; // convert to minutes
$hour_date = $minute_date / 60; // convert to hours
print $hour_date;
if($hour_date > 2){ // change the 2 to whatever you want it to be.
print "more than two hours";
}else{
print "less than two hours";
}
?>