1

So, I'm trying to count the number of hours between a DateTime value and the current date with PHP. I don't want to do it by seconds and then divide it into minutes and then hours, because I'd like for it to count each hour individually. For example, 4PM-5PM would be 1, 5PM-6PM would be 2, and so on.

So if the DateTime was 2012-09-24 7:49:23 and the current DateTime was 2012-09-24 8:00:19 it would output the number 1. And if the DateTime was 2012-09-24 7:49:23 and the current DateTime was 2012-09-24 8:59:45 it would still output 1. (It wouldn't change to 2 until 9:00:00)

The DateTime I'm using for comparison is coming out a database, and if I can figure out how I will make it so that it cuts off the minutes/seconds portion of the DateTime (so that they're 0). If I could do the same with the current DateTime it would be easy. The thing is, I don't know how to do that. So how can I turn 2012-09-24 7:49:23 into 2012-09-24 7:00:00 (It still needs to be in a DateTime format so I can put it back into the MySQL database in a DateTime field)

Thanks!

EDIT: I appreciate both answers I received, but I tried tinkering with them and couldn't get exactly what I wanted. Instead, I was able to come up with on my own (through some more trial and error) what I needed to make this work. I've included it below in case anyone else has a similar issue.

$timea = date_format(date_create(date("c")), 'Y-m-d H:00:00');
$timeb = date_format(date_create($databasedate), 'Y-m-d H:00:00');

//hours
$diff = abs(strtotime($timeb) - strtotime($timea));
$hours = round(($diff/60/60));

That code should all be pretty straightforward and easy to understand. Thanks again everyone :)

4

2 回答 2

0

在 PHP 中有很多方法可以清除日期和时间的各个部分,但是如果您想坚持使用DateTime该类(我强烈推荐),并且您将在多个地方使用它,我建议DateTime您扩展包含该功能的自己的子类:

namespace my\name\space;

class MyWeirdMinuteAndSecondlessDateTime extends \DateTime {
    public function __construct($date, \DateTimeZone $tz = NULL) {
        parent::__construct($date, $tz);

        // Set the time to just the hour.  This is sort of
        // equivalent to the floor() function for floats.
        $this->setTime($this->format('G'), 0, 0);
    }
}
于 2012-09-25T02:48:44.883 回答
0
$time1->setTime($time1->format('G'), 0, 0);
$time2->setTime($time2->format('G'), 0, 0);
$hourdiff = $time2->diff($time1)->format('G');
于 2012-09-25T02:59:39.850 回答