我需要在PHP中检查当前时间是否早于当天下午2点。
以前我用strtotime
检查日期,但这次只涉及时间,所以每天的0.00时会重置时间并将布尔值从false
重置为true
。
if (current_time < 2pm) {
// do this
}
'H'
的文档链接? - Merlyn Morgan-Graham尝试:
if(date("Hi") < "1400") {
}
请参考:http://php.net/manual/zh/function.date.php
H 24-hour format of an hour with leading zeros 00 through 23
i Minutes with leading zeros 00 to 59
1400
应该是一个字符串吗? - user2924019如果您将数字与字符串进行比较或比较涉及数字字符串,则每个字符串都会转换为数字,然后执行数字比较。
。你能获得更好的性能吗?我不知道,请进行基准测试!哪一个更清晰?这取决于您的项目/组织的样式指南以及您更喜欢简洁还是明确。我个人偏好现在是 if((int)date("Hi") < 1400)
,但我不经常使用PHP。 - Merlyn Morgan-Grahamif (time() < strtotime('2 pm')) {
//not yet 2 pm
}
或者也可以明确地传递日期参数
if (time() < strtotime('2 pm ' . date('d-m-Y'))) {
//not yet 2 pm
}
使用24小时制来解决问题,方法如下:
$time = 1400;
$current_time = (int) date('Hi');
if($current_time < $time) {
// do stuff
}
所以,24小时制中的2PM等同于14:00。如果我们从时间中移除冒号,则可以将其作为整数进行比较。
有关日期函数的更多信息,请参阅PHP手册。我使用了以下时间格式:
H = 小时的24小时格式(00至23)
i = 带前导零的分钟数(00至59)
$now = new DateTime();
$twoPm = new DateTime();
$twoPm->setTime(14,0); // 2:00 PM
if ( $now < $twoPm ){ // such comparison exists in PHP >= 5.2.2
// do this
}
否则,如果您正在使用旧版本(例如5.0),则以下内容应该起作用(而且更加简单):
$now = time();
$twoPm = mktime(14); // first argument is HOUR
if ( $now < $twoPm ){
// do this
}
if (date('H') < 14.30) {
$pre2pm = true;
}else{
$pre2pm = false;
}
time()
、date()
和strtotime()
函数:if(time() > strtotime(date('Y-m-d').' 14:00') {
//...
}
尝试使用
if( time() < mktime(14, 0, 0, date("n"), date("j"), date("Y")) ) {
// do this
}
此函数将通过接受两个参数,包含小时和上午/下午的数组,检查它是否在东部标准时间内。
/**
* Check if between hours array(12,'pm'), array(2,'pm')
*/
function is_between_hours($h1 = array(), $h2 = array())
{
date_default_timezone_set('US/Eastern');
$est_hour = date('H');
$h1 = ($h1[1] == 'am') ? $h1[0] : $h1[0]+12;
$h1 = ($h1 === 24) ? 12 : $h1;
$h2 = ($h2[1] == 'am') ? $h2[0] : $h2[0]+12;
$h2 = ($h2 === 24) ? 12 : $h2;
if ( $est_hour >= $h1 && $est_hour <= ($h2-1) )
return true;
return false;
}
current_time
是什么? - KingCrunch2pm
、14
、14:00
等等)时,它们就不再有用了。 - KingCrunch