2016-11-10 151 views
2

我希望輸出爲給定月份和年份中的週日數。計算給定月份和年份的週日數

這是我的代碼:

$months=$_POST['month']; 
$years=$_POST['year'];          
$monthName = date("F", mktime(0, 0, 0, $months)); 
$fromdt=date('Y-m-01 ',strtotime("First Day Of $monthName $years")) . '<br/>'; 
$todt=date('Y-m-d ',strtotime("Last Day of $monthName $years")) . '<br/>'; 

$num_sundays='';     
for ($i = 0; $i < ((strtotime($todt) - strtotime($fromdt))/86400); $i++) 
{ 
    if(date('l',strtotime($fromdt) + ($i * 86400)) == 'Sunday') 
    { 
      $num_sundays++; 
    } 
} 

我沒有得到任何輸出,如果我回聲$ num_sundays。請幫幫我 。我是新來的PHP

+0

'的strtotime($託德)'是空 – devpro

+2

刪除此'。 '
''從兩條線和chk的結果 – devpro

+0

我認爲它也是空的 –

回答

0

獲取當月所有周日見下面的代碼:

function total_sun($month,$year) 
{ 
    $sundays=0; 
    $total_days=cal_days_in_month(CAL_GREGORIAN, $month, $year); 
    for($i=1;$i<=$total_days;$i++) 
    if(date('N',strtotime($year.'-'.$month.'-'.$i))==7) 
    $sundays++; 
    return $sundays; 
} 
echo total_sun(11,2016); 

http://phpio.net/s/l9f

4

你只需要從以下兩行刪除<br>

$fromdt=date('Y-m-01 ',strtotime("First Day Of $monthName $years")) . '<br/>'; 
$todt=date('Y-m-d ',strtotime("Last Day of $monthName $years")) . '<br/>'; 

否則,此將是開始和結束日期的一部分,並且您的strtotime()將返回false。

例子:

<?php 
$months = 12; 
$years=2016;          
$monthName = date("F", mktime(0, 0, 0, $months)); 
$fromdt=date('Y-m-01 ',strtotime("First Day Of $monthName $years")) . '<br/>'; 
$todt=date('Y-m-d ',strtotime("Last Day of $monthName $years")) . '<br/>'; 

var_dump(strtotime($todt)); 
var_dump(strtotime($fromdt)); 
?> 

DEMO:這將返回兩個錯誤。

實施例2:

<?php 
$months = 12; 
$years=2016;          
$monthName = date("F", mktime(0, 0, 0, $months)); 
$fromdt=date('Y-m-01 ',strtotime("First Day Of $monthName $years")) ; 
$todt=date('Y-m-d ',strtotime("Last Day of $monthName $years")); 

var_dump(strtotime($todt)); 
var_dump(strtotime($fromdt)); 
?> 

DEMO:這將返回值

完整的例子:

<?php 
$months = 12; 
$years=2016;          
$monthName = date("F", mktime(0, 0, 0, $months)); 
$fromdt=date('Y-m-01 ',strtotime("First Day Of $monthName $years")) ; 
$todt=date('Y-m-d ',strtotime("Last Day of $monthName $years")); 

$num_sundays='';     
for ($i = 0; $i < ((strtotime($todt) - strtotime($fromdt))/86400); $i++) 
{ 
    if(date('l',strtotime($fromdt) + ($i * 86400)) == 'Sunday') 
    { 
      $num_sundays++; 
    }  
} 
echo "Total Count is: ".$num_sundays; 
?> 

DEMO:這將返回4日

0

工作示例dorcode calculation

$startd="31-7-2006 15:30:00"; 
$endd="31-7-2007 15:30:00"; 

$startDate=$startd; 
$endDate=$endd; 
$startDate1 = strtotime($startDate); 
$endDate1 = strtotime($endDate); 
if($startDate1>$endDate1) 
{ 
$startDate1 = strtotime($endDate); 
$endDate1 = strtotime($startDate); 
} else { 
$startDate1 = strtotime($startDate); 
$endDate1 = strtotime($endDate); 
} 
$p=0; 
for($i = strtotime("Sunday", $startDate1); $i <= $endDate1; 
$i =strtotime('+1 week', $i))  
{ 
$p++; 
echo $p.": ".date('F d, Y', $i)."<br>"; 
} 
相關問題