Php检查时间字符串整个小时是否像“上午8:00”

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (168)

I have series of time strings like "8:00am", "8:15am", "8:30am" I also have timestamps for these times as keys of the arrays where as times are values so array would be like this:

Note: Timestamps are dummy in this example

array(
144441415=>"8:00am", 
1444784744=>8:30am
...
.....
);

I would like to know if hour is whole hour for example "8:00am", "9:00am" are whole hours but "8:45am" or "9:30am" are not whole hours. I would like to filter whole hours from array as mentioned above. Thanks.

提问于
用户回答回答于

你可以这样做:

$times = array(
    144441415=>"8:00am", 
    1444784744=>"8:30am",
    1444784745=>"8:45am",
    1444784746=>"9:00am",
    1444784747=>"10:00am",

);

foreach ($times as $time) {
    if (date("H:00:00", strtotime($time)) == date("H:i:00", strtotime($time))) {
        echo '<br>Whole Hour: '.$time;
    }
    else {
        echo '<br>Not Whole Hour: '. $time;
    }
}
用户回答回答于

Thank you Rudie I was able to get whole hour from number of seconds, thank you for your hint, so I did something like this:

//Loop through each hour of the day by getting both key and value
foreach( $hours_of_day $timestamp=>$time_string )
{
    //If timestamp mod by number of seconds in hours is zero this means whole hour
    if( ($timestamp%3600) == 0 )
    {
        echo "Whole hour = $timestring<br />";
    }
}

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励