dso89762 2015-07-28 21:38
浏览 24

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?

  • 写回答

2条回答 默认 最新

  • douwenan9849 2015-07-28 21:44
    关注

    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.

    评论

报告相同问题?