我有两个约会对象说10/01/2016 00:00:00到18/01/2016 08:00:00。我想检查这两个日期是在星期五上午12点到星期日12点之间,那么如何找出小时差异?
PHP代码 -
$t1 = StrToTime($date2);
$t2 = StrToTime($date1);
$diff = $t1-$t2;
$hours = abs($diff / ( 60 * 60 ));
我严重陷入困境。请有人帮忙。
先谢谢。
答案 0 :(得分:0)
如果我正确地理解了你的问题,你想测试一下这个日期是星期五还是星期六,与他们相距多远无关。
您可以使用DateTime对象的format()
函数获取日期的工作日,然后测试它是星期五(5)还是星期六(6):
$t1 = DateTime::createFromFormat("d/m/Y H:i:s", "10/01/2016 00:00:00");
$t2 = DateTime::createFromFormat("d/m/Y H:i:s", "18/01/2016 08:00:00");
function testDate($date) {
$d = $date->format("N");
if ($d == 5) return true;
if ($d == 6) return true;
return false;
}
$d1 = testDate($t1);
$d2 = testDate($t2);
var_dump($d1, $d2);
// Result:
// bool(false)
// bool(false)
然后您可以使用DateTime::diff()
函数来获得差异:
$diff = $t1->diff($t2);
var_dump($diff);
结果:
object(DateInterval)#3 (15) {
["y"]=>
int(0)
["m"]=>
int(0)
["d"]=>
int(8)
["h"]=>
int(8)
["i"]=>
int(0)
["s"]=>
int(0)
["weekday"]=>
int(0)
["weekday_behavior"]=>
int(0)
["first_last_day_of"]=>
int(0)
["invert"]=>
int(0)
["days"]=>
int(8)
["special_type"]=>
int(0)
["special_amount"]=>
int(0)
["have_weekday_relative"]=>
int(0)
["have_special_relative"]=>
int(0)
}
所以,8天($diff['days']
)和8小时($diff['h']
)
答案 1 :(得分:0)
您可以使用:
$date1 = "2016-08-14 00:00:00"; //more higger day
$date2 = "2016-08-13 00:00:00";
$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));
$hours = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24)/ (60*60));
$minuts = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60)/ 60);
$seconds = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60 - $minuts*60));
printf("%d years, %d months, %d days, %d hours, %d minuts\n, %d seconds\n", $years, $months, $days, $hours, $minuts, $seconds);
输出:0年,0个月,1天,0小时,0分钟,0秒
现在,你可以这样做:
$date1 = "2016-08-14 00:00:00"; //more higger day
$date2 = "2016-08-13 00:00:00";
$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));
$hours = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24)/ (60*60));
echo "Totals hours: ".($days*24 + $hours);
返回24(您可以将年,月等乘以)