2016-12-30 6 views
1

私は、ユーザーに「最初の試験」の日付を入力させ、その日付を今日の日付と比較し、それらの間の違いがある場合には警告/ 2つの日付は特定の金額です(残りの試験は最初の試験から18ヶ月以内に完了する必要があります)。条件文の日付間の違いを比較する方法が問題になっています。つまり、$differenceと「18ヶ月」や「2ヶ月」などを比較するにはどうすればいいですか。正しい方向性は非常に高く評価されます。PHP - この条件文の日付/期間を比較する方法

コード:

<?php 

// Set first exam date 
$firstexamdate = "2015-08-20"; 

// Work out date that is 18 months from first exam date 
$add_18_months = strtotime($firstexamdate . ' + 18 months'); 
$eighteen_months_time = date('Y-m-d',$add_18_months); 

// Check 
echo "Date of first exam: " . $firstexamdate . "<br>"; 
echo "18 months from this date: " . $eighteen_months_time . "<br>"; 

// Work out diff between cut-off date and today 
$today = date('Y-m-d'); 
$date1 = new DateTime($eighteen_months_time); 
$date2 = new DateTime($today); 
$difference = $date1->diff($date2); 

// Display 
echo "Difference/time remaining: " . $difference->y . " years, " . $difference->m . " months, " . $difference->d . " days " . "<br"; 

// BELOW CODE NOT WORKING 

// Display $difference as string 
echo $difference->format('Y-m-d'); 

// Output correct warning colour 
if ($difference <= /* 18 months */ and >= /* 6 months */ { 
    echo "Green warning: At least 6 months left."; 
} elseif ($difference <= /* 5 months */ and >= /* 2 months */ { 
    echo "Orange warning: Less than 5 months left."; 
} elseif ($difference <= /* 1 months */ and >= /* 0 months */ { 
    echo "Red warning: Less than one month left."; 
} 

?> 

答えて

2

あなたは$の差分オブジェクトのプロパティを使用することができます。

if ($difference->days <= (18 * 30) && $difference->days >= (6 * 30) { 
    echo "Green warning: At least 6 months left."; 
} 

プロパティについて日PHPのドキュメントで

の場合DateIntervalオブジェクトはDateTime ::によって作成されましたdiff()の場合、この は開始日と終了日の間の合計日数です。 それ以外の場合、日数はFALSEになります。

http://php.net/manual/en/class.dateinterval.php

EDIT

あなたは6と18ヶ月必要がある場合は、正確にあなたがこのアプローチを使用することができます。

$targetDate = new DateTime('20170529'); //here your target date; 
$now = new DateTime(); //by default today; 
$min = clone $targetDate; 
$min->add(new DateInterval('P6M')); 
$max = clone $targetDate; 
$max->add(new DateInterval('P18M')); 
if($now >= $min && $now <= $max){ 
// your code here 
} 
+1

28月29日から31日までの数ヶ月にもかかわらず、これは動作しますか? – sinesine

+0

「20170529」は確定的に次の日付ではありません – MaxZoom

1

あなたは数ヶ月の番号を取得するためにdate-diff(..)機能を使用することができます2つの日付オブジェクトの間

<?php 
// Set first exam date 
$firstexamdate = "2015-08-20"; 
// Work out date that is 18 months from first exam date 
$nextDate = new DateTime($firstexamdate); 
$nextDate->add(new DateInterval('P18M')); 
// Calculate nr of months 
$today = new DateTime(); 
$interval = date_diff($today, $nextDate); 
$months = $interval->y * 12 + $interval->m; 

// Output correct warning color 
if ($months < 18 and $months>= 6) { 
    echo "Green warning: At least 6 months left."; 
} elseif ($months < 6 and $months>=1) { 
    echo "Orange warning: Less than 5 months left."; 
} elseif ($months < 1) { 
    echo "Red warning: Less than one month left."; 
} 

?>