2016-04-22 43 views
0

我一直在尋找如何檢查日期是否介於其他日期之間,並且從我讀過的內容看來,我可以使用如果在php中使用date()函數聲明我在大多數情況下都使用了函數,但有時它是錯誤的。我不知道爲什麼。檢查一個日期是否在PHP的其他日期之間沒有按照它應該

function checkToday($date1, $date2, $today) 
{ 

    if($date1 < $today && $date2 > $today) 
    { 
     return "between"; 
    } elseif ($date1 < $today) { 
     return "before"; 
    } else { 
     return "after"; 
    } 
} 

我與許多不同的日期,稱它與它們都顯示,除了這一個工作:2016年7月3日19-05-2016 22-前:

$startDate = date('d-m-Y', strtotime("07-03-2016")); 
$endDate = date('d-m-Y', strtotime("19-05-2016")); 
$currDate= date('d-m-Y'); 
$check = checkToday($startDate, $endDate, $currDate); 
echo $check.' '; 
echo $startDate.' '; 
echo $endDate.' '; 
echo $currDate.' '; 

該輸出04-2016

但是,很顯然22-04-2016在2016年7月3日和19-05-2016

任何想法之間?

謝謝

+0

比較timestaps而不是srings – splash58

回答

1

您將日期比較爲字符串,這就是爲什麼它不能正常工作。

您需要比較時間戳(由time()strtotime()返回)或使用DateTime對象。

實施例與日期時間:

<?php 

function checkToday($date1, $date2, $today) 
{  
    if($date1 < $today && $date2 > $today) 
    { 
     return "between"; 
    } elseif ($date1 < $today) { 
     return "before"; 
    } else { 
     return "after"; 
    } 
} 

$startDate = new DateTime("2016-03-07"); 
$endDate = new DateTime("2016-05-19"); 
$currDate= new DateTime(); 
$check = checkToday($startDate, $endDate, $currDate); 

echo $check.' '; // Returns between 
echo $startDate->format("d-m-Y").' '; 
echo $endDate->format("d-m-Y").' '; 
echo $currDate->format("d-m-Y").' '; 
0

PHP中多一個功能strtotime。你應該使用這個函數來比較PHP中的日期,如下所示

function checkToday($date1, $date2, $today) 
{  
    if(strtotime($date1) < strtotime($today) && strtotime($date2) > strtotime($today)) 
    { 
     return "between"; 
    } elseif (strtotime($date1) < strtotime($today)) { 
     return "before"; 
    } else { 
     return "after"; 
    } 
} 
+0

我知道它一定是簡單的東西!非常感謝。這固定它 –

+0

歡迎。接受答案並加註。 –

+0

我還沒有足夠的'聲望'來這樣做。它不會公開顯示。 –

相關問題