2017-05-31 30 views
0

我遇到問題。我正在嘗試使用PHP比較當年與某一年的情況,但根據我的編碼,它總是返回true。我在下面解釋我的代碼。在使用PHP比較兩年時始終保持真實

$datestr="2020-2029"; 
$curryear=date("Y"); 
$yearArr=explode("-",$datestr); 
$strYear=strtotime($yearArr[0]); 
if($curryear < $strYear){ 
    $flag=true; 
}else{ 
    $flag=false; 
} 
echo $flag; 

在這裏,我需要-之前的第一年應該是本年度的before year/same year。請幫我解決這個問題。

+0

$ strYear = strtotime($ yearArr [0]); 將返回2016年的時間戳,它返回1496261760,並且始終大於2017年。 使用 '$ strYear = $ yearArr [0];' –

+0

爲什麼你想要做時間? – sumit

回答

2

你不需要strtotime(),因爲這個函數返回時間戳,你只需要一年的字符串。使用此:

$datestr="2016-2029"; 
$curryear=date("Y"); 
$yearArr=explode("-",$datestr); 
$strYear=$yearArr[0]; 
if($curryear < $strYear){ 
    $flag=true; 
}else{ 
    $flag=false; 
} 
echo $flag; 
0

您已經有了一年的4位數表示(2016),但你從1970年開始使用strtotime(),這是一個更大的數字時,將其轉換爲秒(var_dump($strYear);將顯示int(1496254560) )。你只是想刪除該功能,否則你比較2017 < 1496254560

$datestr = "2016-2029"; 
$curryear = date("Y"); 
$yearArr = explode("-",$datestr); 
$strYear = $yearArr[0]; 
if ($curryear < $strYear) { 
    $flag = true; 
} else { 
    $flag = false; 
} 

Live demo

0

這裏的響應:

php > var_dump(strtotime("2016")); 
php shell code:1: 
int(1496261760) 

使用的strtotime,一個2016字符串被轉換爲一個整數。而你的一年總是會低於這個數字。

PHP自動轉換變量。

php > var_dump("2016" < 2015); 
php shell code:1: 
bool(false) 
php > var_dump("2016" < 2018); 
php shell code:1: 
bool(true) 

要在家中嘗試此操作,請在您的bash中運行「php -a」。您可以在飛行中嘗試使用PHP。