2013-04-28 26 views
1

考慮到閏年,我需要在任何月份提取總小時數,只考慮MONTH和YEAR。提取特定月份和年份的總小時數,考慮到閏年,使用PHP

這是到目前爲止我的代碼...

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

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

獲取下個月第一天的時間戳和當前月份第一天的時間戳並減去。 – PeeHaa 2013-04-28 16:56:14

+0

您是否需要允許在一個月內發生夏時制變化? – 2013-04-28 17:10:27

+0

@MarkBaker號不是。 – lloyd 2013-04-28 17:14:23

回答

1

你可以這樣做:

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

這對於DST會很好嗎? – PeeHaa 2013-04-28 16:59:20

+0

對不起,我只有MONTH和YEAR。 – lloyd 2013-04-28 16:59:38

+0

然後將默認日期設置爲'01',只要有效,哪一天都不重要。 – 2013-04-28 17:00:44

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; 
+0

謝謝Ben,你的代碼也能工作! – lloyd 2013-04-29 13:14:00

+0

謝謝@lloyd,不要忘記接受你的最終答案,但:-) – 2013-04-29 14:02:49

+0

我會記住的! – lloyd 2013-04-29 14:27:09

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); 
+0

謝謝,讓我測試一下,看看。 – lloyd 2013-04-28 17:06:08

+0

謝謝巴巴。你的代碼工作! – lloyd 2013-04-29 13:16:04

+0

不用客氣 – Baba 2013-04-29 13:22:01

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」,那麼你需要將字符串解析成整數,它可以像這樣

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

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