2 回答

TA貢獻1799條經(jīng)驗 獲得超9個贊
直接比較時間戳更簡單 你不需要非常復(fù)雜的邏輯
$current_time = (new DateTime('now'))->getTimestamp();
if ($current_time < strtotime('01-04-2019')) {
echo "discount quarter 1";
} else if ($current_time < strtotime('01-07-2019')) {
echo "discount quarter 2";
} else if ($current_time < strtotime('01-10-2019')){
echo "discount quarter 3";
} else {
echo "discount quarter 4";
}

TA貢獻1803條經(jīng)驗 獲得超3個贊
正如所指出的,您正在比較 dmY 格式的字符串,這會產(chǎn)生意想不到的結(jié)果。相反,您最好只比較時間戳本身。
此代碼還簡化了if... elseif...結(jié)構(gòu),因為您可以假設(shè)它是 > 2 季度(例如),那么您不需要檢查日期是否小于。我也已將其更改為,<=以便檢查宿舍本身(您必須決定是否要包含日期)...
$current_time = strtotime("now");
$quarter1 = strtotime('01-01-2019');
$quarter2 = strtotime('01-04-2019');
$quarter3 = strtotime('01-07-2019');
$quarter4 = strtotime('01-10-2019');
if ( $current_time >= $quarter1 ) {
if ( $current_time <= $quarter2 ){
// quarter 1
echo "discount quarter 1";
}
elseif ( $current_time <= $quarter3 ){
// quarter 2
echo "discount quarter 2";
}
elseif ( $current_time <= $quarter4){
// quarter 3
echo "discount quarter 3";
}
else {
// quarter 4
echo "discount quarter 4";
}
}
- 2 回答
- 0 關(guān)注
- 184 瀏覽
添加回答
舉報