2017-04-21 7 views
-1

過ぎて行く、それは私が日付を入れた状態で間違った出力を与える「2017年1月30日」のstrtotime 1月が来月

function date_diff($min,$max) 
{ 
    $d1 = strtotime($min); 
    $d2 = strtotime($max); 
    $min_date = min($d1, $d2); 
    $max_date = max($d1, $d2); 
    $count=$i = 0; 
    while (($min_date = strtotime("+1 MONTH", $min_date)) <= $max_date) 
    { 
     echo "<br/>"; 
     echo date('Y-m-d',$min_date)."--------".date("Y-m-d",$max_date); 
    } 

} 

私が呼び出していますこのような日付の機能:

date_diff("2016/12/30","2017/07/30"); 

機能上からの出力は、次のとおりです。

2017-01-30--------2017-07-30 
2017-03-02--------2017-07-30 // wrong calculation on this line 
2017-04-02--------2017-07-30 
2017-05-02--------2017-07-30 
2017-06-02--------2017-07-30 
2017-07-02--------2017-07-30 

の予想される出力

2017-01-31--------2017-07-30 
2017-02-28--------2017-07-30 
2017-03-31--------2017-07-30 
2017-04-30--------2017-07-30 
2017-05-31--------2017-07-30 
2017-06-30--------2017-07-30 
+3

ことが30日追加して、2月30日がないので、ウィッヒは3月2日になります。 – Jerodev

+0

あなたはどんな出力を期待していますか? 2月30日は存在しません – Joni

+0

ええ私は解決策を知っています –

答えて

1

はmktimeを使用ここに答えを提供する私のショットです。

コード:

function date_func($d1,$d2){ 
    $min=date("Y-m-t",strtotime(min([$d1,$d2]))); // always the last day of the month 
    $max=date("Y-m-d",strtotime(max([$d1,$d2]))); 
    $month_count=0; 
    while(($min=date("Y-m-t",strtotime("$min +1 day")))<$max){ 
     ++$month_count; 
     echo "$min--------$max\n"; 
    } 
    echo "Month Count: $month_count\n"; // I assume you only want the count at the end 
} 
date_func("2016/12/30","2017/07/30"); // I had to rename your function to avoid an error 

出力:

2017-01-31--------2017-07-30 
2017-02-28--------2017-07-30 
2017-03-31--------2017-07-30 
2017-04-30--------2017-07-30 
2017-05-31--------2017-07-30 
2017-06-30--------2017-07-30 
Month Count: 6 
+0

出力がありました。私の問題を解決しましたthanks @mickmackusa –

1

それは私があなたの質問を誤解していていること(そうであっても)可能ですが、月の違いを見つけ、その後、

$min="2016/12/30"; 
$max="2017/07/30"; 
$ts1 = strtotime($max); 
$ts2 = strtotime($min); 

$year1 = date('Y', $ts1); 
$year2 = date('Y', $ts2); 

$month1 = date('m', $ts1); 
$month2 = date('m', $ts2); 

$diff = (($year1 - $year2) * 12) + ($month1 - $month2); 

for ($i = 1; $i < $diff; $i++) 
     { 
      $last_day=date('m-t-Y', strtotime(date('Y-m-d', mktime(0, 0, 0, $i, 1, $year1)))); 
      echo $last_day."--------".date('Y-m-d',$ts1); 
      echo "<br>"; 
     } 

出力

01-31-2017--------2017-07-30 
02-28-2017--------2017-07-30 
03-31-2017--------2017-07-30 
04-30-2017--------2017-07-30 
05-31-2017--------2017-07-30 
06-30-2017--------2017-07-30 
+0

2つの日付の間に何ヶ月の間違いがあるかチェックしたいだけですが、その間隔は浮動小数点でなければなりません。 –

+0

例えば2017-07-30から2018-01-30までOKですが2017-07-30〜2018-02-03はokwではありません –

関連する問題