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

使用PHP提取特定月份和年份的总小时数,考虑闰年,php,Php,我需要提取任意月份的总小时数,只考虑月份和年份,并考虑闰年 这是我到目前为止的代码 $MonthName = "January"; $Year = "2013"; $TimestampofMonth = strtotime("$MonthName $Year"); $TotalMinutesinMonth = $TimestampofMonth / 60 // to convert to minutes $TotalHoursinMonth = $TotalMinutesinMont

我需要提取任意月份的总小时数,只考虑月份和年份,并考虑闰年

这是我到目前为止的代码

$MonthName = "January";
$Year = "2013";

$TimestampofMonth = strtotime("$MonthName  $Year");
$TotalMinutesinMonth = $TimestampofMonth / 60     // to convert to minutes
$TotalHoursinMonth = $TotalMinutesinMonth / 60    // to convert to hours
您可以这样做:

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

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

您可以使用
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);
$date=“2013年1月”//你只知道月份和年份
$workHours=10;//一天10小时
$start=DateTime::createFromFormat(“F Y d”,“$date 1”);//先添加
printf(“%s hr(s)”,$start->format(“t”)*24);
//如果你只看工作日
$end=clone$start;
$end->modify(sprintf(“%d天”),$start->format(“t”)-1);
$interval=新日期间隔(“P1D”);//间隔
var_dump($start,$end);
$hr=0;
foreach(新的DatePeriod($start、$interval、$end)作为$day){
//不包括星期日和星期日
如果($day->format('N')<6){
$hr+=$workHours;//添加工作时间
}
}
printf(“%s hr(s)”,$hr);

您可以使用上述函数检索一个月内的总天数(考虑闰年),然后将该值乘以24 另外,您还可以使用cal_days_in_month函数,但它只支持PHP4.0.7及更高版本的PHP版本


如果您使用上面的“get_day_in_month”,那么您需要将字符串解析为整数,可以这样做

一个月

一年

获取下个月第一天的时间戳、本月第一天的时间戳和减法。您需要考虑本月发生的夏令时变化吗?@MarkBaker不需要。不需要。升级PHP并使用DateTime对象…这对DST来说会好吗?对不起,伙计,我只有月份和年份。然后将默认日期设置为
01
,只要日期有效,这与日期无关。@RyanNaddy你什么意思,兄弟?@PeeHaa埽 并非所有地方都有夏令时,比如亚利桑那州。世界上大约有50%的人没有DST:谢谢你,劳埃德,别忘了接受你最后的答案:-)劳埃德,你知道怎么做吗?是的,我想是的。我只需点击“向上”箭头左边的最佳职位的权利?我刚刚注意到你的贡献和Ryan Naddy的完全一样。我想,当@Ryan第一次得到他们的贡献时,给他一点荣誉吧。单击要接受的答案旁边的勾号。向上投票只是说这个答案是好的,谢谢你:-)
<?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);


?>