[英]How to get total days of each month in a leap year
我正在嘗試創建一個腳本函數,該函數可以獲取一年中每個月的總天數。 我的想法是創建最近12個月的報告,我們有可能獲得leap年,但我的計算並未涵蓋這一點。 我嘗試創建一個代碼,該代碼映射除了leap年的2月份為29天的所有月份。
這是我的代碼:
public function checkMes(){
// ----------------------------------- Verificar se o mes tem 30 ou 31 ou 28 dias -------------
$month = array();
for ($i = -10; $i < 0; $i++)
{
$check_month = date('m');
if($check_month == '01' || $check_month == '03' || $check_month == '05' || $check_month == '07' || $check_month == '08' || $check_month == '10' || $check_month == '12')
{
$month[] = date('m/Y',strtotime('+'.$i.' months + 1 days'));
}elseif($check_month == '02'){
$month[] = date('m/Y',strtotime('+'.$i.' months - 2 days'));
}else{
$month[] = date('m/Y',strtotime('+'.$i.' months'));
}
}
return $month;
}
誰能幫我這個?
[UPDATE]
由於我的數據需要計算和報告,因此我需要知道2月是29日還是28日。 如果我在2月29日有交易,則需要在我的報告中考慮,直到2月28日
date('t')
給出給定月份的天數。
http://php.net/manual/en/function.date.php
因此,可以代替if-elseif-else塊:
$month[] = date('m/Y',strtotime('+'.date('t').' days'));
您可以使用date("t")
:
<?php
$number_of_days_in_month = date('t');
?>
這很容易。 創建一個函數,該函數計算當前年份是4或400的整數倍,還是100的整數倍。
讓我闡明一些腳本代碼的含義:
首先,創建一個小函數來獲取當前年份並進行計算。 它看起來像這樣:
public function leap($ano)
{
$leap = false;
if ( (($ano%4) == 0 && ($ano%100) != 0) || ($ano%400) == 0 )
{
$leap = true;
}
return $leap;
}
現在,您需要修改當前函數並添加以下我注釋過的代碼:
public function checkMes(){
$ano = date('Y'); //add this line
$this->leap($ano); // add this line
// ----------------------------------- Verificar se o mes tem 30 ou 31 ou 28 dias -------------
$month = array();
for ($i = -10; $i < 0; $i++)
{
$check_month = date('m');
if($check_month == '01' || $check_month == '03' || $check_month == '05' || $check_month == '07' || $check_month == '08' || $check_month == '10' || $check_month == '12')
{
$month[] = date('m/Y',strtotime('+'.$i.' months + 1 days'));
}elseif($check_month == '02'){
if(isset($leap)){ //add this line
$month[] = date('m/Y',strtotime('+'.$i.' months - 1 days')); //add this line
}else{ //add this line
$month[] = date('m/Y',strtotime('+'.$i.' months - 2 days')); //add this line
} //add this line
}else{
$month[] = date('m/Y',strtotime('+'.$i.' months'));
}
}
return $month;
}
希望對您有幫助。
我知道要用PHP解決它,您的條件是錯誤的:
嘗試這個:
$arr = array(1944, 2011, 2012, 2013, 2014, 1986, 1800, 1900, 2000, 2056);
function leapYear($year){
if(($year % 4) == 0 && ($year % 100) != 0){
return true;
}
else{
return false;
}
}
for($i = 0; $i < count($arr) ; $i++){
$r = leapYear($arr[$i]);
if($r){
echo 'Lepo year: ' . $arr[$i] . '<br>';
}else{
echo 'Not Leap year: ' . $arr[$i] . '<br>';
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.