php - 如何获得给定月份的小时数?

I found that I can get number of days using

cal_days_in_month()

So I can use cal_days_in_month() * 24 to get number of hours.

But is there a direct function to get the number of hours in given month?

This function should get you going what you're looking for:

function cal_hours_in_month($month = false, $year = false) {
    if($year === false) $year = date('Y');
    if($month === false) $month = date('n');
    $first = mktime(0, 0, 0, $month, 1, $year);
    $last = mktime(23, 59, 00, $month+1, 0, $year);

    return ($last - $first) / 3600;
}
echo cal_hours_in_month(2015, 7);

Borrowed code from this answer for expediency.

This should have the added benefit of compensating for daylight savings time, though you may want to make sure your date_default_timezone_set() is correct.

Trivial point of interest: Keep in mind that as adjustments are occasionally made to DST, getting the duration of a month some time in the future may ultimately end up being inaccurate.

My environment (America/Chicago zone) returns 743.983 (rounded) for this month, July 2015.

echo cal_hours_in_month(2, 2015); returns 671.983 (non-leap-year)

echo cal_hours_in_month(2, 2016);returns 695.983 (leap-year)

EDIT: Made all parameters optional.

Here's an approach that respects DST and the timezone.

$timezone = new DateTimezone('Europe/Berlin');
$begin = new DateTime('2015-03-01 00:00:00', $timezone);
$end = new DateTime('2015-03-31 23:59:59', $timezone);
$interval = new DateInterval('PT1H');
$period = new DatePeriod($begin, $interval, $end);

$count = 0;

foreach ($period as $date)
    ++$count;

echo $count; // 743 for March in Germany

Unfortunately, DatePeriod implements only Traversable, without support for count(), so we have to iterate over the dates and count them. (If anyone has got a better idea, let's hear it.)