2014-12-04 34 views
0

我有两个日期。开始日期和结束日期。使用这些日期我必须找到重复日期。每月一次发生的PHP

例如:

(1) start date = 2014-01-01 
    end date = 2014-05-01 

    expected output: 

     2014-01-01 
     2014-02-01 
     2014-03-01 
     2014-04-01 
     2014-05-01 

(2) start date = 2014-01-31 
    end date = 2014-05-01 

    expected output: 

     2014-01-31 
     2014-02-28 
     2014-03-31 
     2014-04-30 

表示不跳过一个月,如果一个月在这种情况下,利用每月的最后一天跳过。如何实现这件事?

我使用下面的代码,但我加入日期起计1个月,因此跳过月:

$start = strtotime($start_date); 
$end = strtotime($end_date); 
$total_dates = array(); 
for($i=$start; $i<=$end;) 
{ 
    $date = date('Y-m-d',$start); 
    if($i>$start) 
    {     
     $next_date = date('Y-m-d',strtotime($date . "+1 month")); 
     $start = strtotime($next_date);         
    } 
    else 
    { 
     $next_date = date('Y-m-d',$start); 
    } 
    $total_dates[] = $next_date; 

    $date1 = new DateTime($date); 
    $newdate = date('Y-m-d',strtotime($date . "+1 month")); 
    $date2 = new DateTime($newdate); 

    $diff = $date2->diff($date1)->format("%a"); 
    /* Find diff between two dates */ 
    $i = (($i*1)+(86400*$diff)); //seconds in 1month 
} 
print_r($total_dates); 

因此,在短期:

start date = 2014-01-01 
end date = 2014-05-01 

expected output: 

2014-01-31 
2014-02-28 
2014-03-31 
2014-04-30 

current output: 

2014-01-31 
2015-03-03 
2015-04-03 

回答

1

检查这个

$start_date = '2015-01-31'; 
$end_date = '2016-06-01'; 
$start_date=date('Y-m-1', strtotime($start_date)); 
$diff = abs(strtotime($end_date) - strtotime($start_date)); 
$years = floor($diff/(365*60*60*24)); 
$months = floor(($diff - $years * 365*60*60*24)/(30*60*60*24)); 

if($years>0){$loop=$years*12+$months;}else{$loop=$months;} 

for($i=1; $i<=$loop+1;$i++) 
{ 


    $total_dates[] =$a= date('Y-m-t', strtotime($start_date)); 
    $start_date = date('Y-m-d',strtotime($start_date . "+1 month")); 

} 
print_r($total_dates); 

//输出
Array ([0] => 2015-01-31 [1] => 2015-02-28 [2] => 2015-03-31 [3] => 2015-04-30 [4] => 2015-05-31 [5] => 2015-06-30 [6] => 2015-07-31 [7] => 2015-08-31 [8] => 2015-09-30 [9] => 2015-10-31 [10] => 2015-11-30 [11] => 2015-12-31 [12] => 2016-01-31 [13] => 2016-02-29 [14] => 2016-03-31 [15] => 2016-04-30 [16] => 2016-05-31 [17] => 2016-06-30)

+0

感谢您的答案..但检查你的代码与这个开始日期'2015-01-31'.....这将跳过二月。 – DS9 2014-12-04 12:39:36

+0

@ DS9现在检查这个。更新代码 – 2014-12-04 12:48:04

0

尝试......

<?php 
$start_date = "2014-01-01"; 
$end_date = "2014-05-01"; 
$d = date_parse_from_format("Y-m-d", $start_date); 
$start= $d["month"]; 

$d1 = date_parse_from_format("Y-m-d", $end_date); 
$end= $d1["month"]; 
$array=array(); 
$array[]=date('Y-m-t', strtotime($start_date)); 
for($i=$start;$i<$end;$i++) 
{ 
$str=explode("-",$start_date); 

$mon=$str[1]+$i; 
$newdate=$str[0]."-".$mon."-".$str[2]; 
$array[]=date('Y-m-t', strtotime($newdate)); 
} 

print_r($array); 

output: 

2014-01-31 
2014-02-28 
2014-03-31 
2014-04-30 
2014-05-31 
+0

谢谢你的回答,但它不工作..如果开始日期是'2014-12-01' – DS9 2014-12-04 12:34:46

相关问题