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

时间:2013-04-28 16:53:26

标签: 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

4 个答案:

答案 0 :(得分:1)

你可以这样做:

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

答案 1 :(得分:1)

计算出当月的天数,然后乘以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;

答案 2 :(得分:0)

您可以使用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);

答案 3 :(得分:0)

<?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”,那么您需要将字符串解析为整数,这可以像这样完成

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

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