使用PHP提取特定月份和年份的总小时数,并考虑闰年


extract total hours in a particular MONTH and YEAR, taking into account leap years, using PHP

我需要提取任何月份的总小时数,只给定month和YEAR,并考虑闰年。

这是我迄今为止的代码。。。

$MonthName = "January";
$Year = "2013";
$TimestampofMonth = strtotime("$MonthName  $Year");
$TotalMinutesinMonth = $TimestampofMonth / 60     // to convert to minutes
$TotalHoursinMonth = $TotalMinutesinMonth / 60    // to convert to hours

只需计算出一个月的天数,然后乘以24,如下所示:

// Set the date in any format
$date = '01/01/2013';
// another possible format etc...
$date = 'January 1st, 2013';
// Get the number of days in the month
$days = date('t', strtotime($date));
// Write out the days
echo $days;

您可以这样做:

<?php
$MonthName = "January";
$Year = "2013";
$days = date("t", strtotime("$MonthName 1st, $Year"));
echo $days * 24;

您可以使用DateTime::createFromFormat,因为您没有日

$date = DateTime::createFromFormat("F Y", "January 2013");
printf("%s hr(s)",$date->format("t") * 24);

好吧,如果你正在考虑工作日,这是一种不同的方法

$date = "January 2013"; // You only know Month and year
$workHours = 10; // 10hurs a day
$start = DateTime::createFromFormat("F Y d", "$date 1"); // added first
printf("%s hr(s)", $start->format("t") * 24);
// if you are only looking at working days
$end = clone $start;
$end->modify(sprintf("+%d day", $start->format("t") - 1));
$interval = new DateInterval("P1D"); // Interval
var_dump($start, $end);
$hr = 0;
foreach(new DatePeriod($start, $interval, $end) as $day) {  
    // Exclude sarturday & Sunday
    if ($day->format('N') < 6) {
        $hr += $workHours; // add working hours
    }
}
printf("%s hr(s)", $hr);
<?php
function get_days_in_month($month, $year)
{
  return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year %400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31);
}
$month = 4;
$year = 2013;
$total_hours = 24 * get_days_in_month($month, $year);

?>

您可以使用上面的函数来检索一个月中考虑闰年的总天数,然后将该值乘以24此外,您还可以使用cal_days_in_month函数,但它只支持PHP 4.0.7及更高版本的PHP构建。


如果你使用上面的"get_day_in_month",那么你需要将字符串解析为整数,这可以像一样完成

月份<?php $date = date_parse('July'); $month_int = $date['month']; ?>

<?php $year_string = "2013" $year_int = (int) $year_string ?>