年份日期中 4 个期间之间的折扣文本 PHP

我是 PHP 的初学者,经过大量搜索,我在这里询问。


我想制作一个文本来回应那个时期的折扣。有 4 个时期 jan - mar、apr - jun、jul - sep、okt - dec(每个季度)。


但即使我现在在 juli,它仍然显示第 4 季度的折扣。我认为它只看当天的价值,而不是月份。


另一个问题是,如何将当前时间更改为静态日期,以便我可以使用不同的日期进行测试。


I made the following code:


$current_time = date('d-m-Y');

$quarter1 = date('d-m-Y', strtotime('01-01-2019'));

$quarter2 = date('d-m-Y', strtotime('01-04-2019'));

$quarter3 = date('d-m-Y', strtotime('01-07-2019'));

$quarter4 = date('d-m-Y', strtotime('01-10-2019'));


if (($current_time > $quarter1 && $current_time < $quarter2 && $current_time < $quarter3 && $current_time < $quarter4)){

    // quarter 1

    echo "discount quarter 1";

}

elseif (($current_time > $quarter2 && $current_time < $quarter3 && $current_time < $quarter4)){

    // quarter 2

    echo "discount quarter 2";

}

elseif ($current_time > $quarter3 && $current_time < $quarter4){

    // quarter 3

    echo "discount quarter 3";

}

else {

    // quarter 4

    echo "discount quarter 4";

}


慕容3067478
浏览 160回答 2
2回答

扬帆大鱼

直接比较时间戳更简单 你不需要非常复杂的逻辑&nbsp; &nbsp; $current_time = (new DateTime('now'))->getTimestamp();&nbsp; &nbsp; if ($current_time < strtotime('01-04-2019')) {&nbsp; &nbsp; &nbsp; &nbsp; echo "discount quarter 1";&nbsp; &nbsp; } else if ($current_time < strtotime('01-07-2019')) {&nbsp; &nbsp; &nbsp; &nbsp; echo "discount quarter 2";&nbsp; &nbsp; } else if ($current_time < strtotime('01-10-2019')){&nbsp; &nbsp; &nbsp; &nbsp; echo "discount quarter 3";&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; echo "discount quarter 4";&nbsp; &nbsp; }

繁星点点滴滴

正如所指出的,您正在比较 dmY 格式的字符串,这会产生意想不到的结果。相反,您最好只比较时间戳本身。此代码还简化了if... elseif...结构,因为您可以假设它是 > 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 )&nbsp; &nbsp; {&nbsp; &nbsp; if ( $current_time <= $quarter2 ){&nbsp; &nbsp; &nbsp; &nbsp; // quarter 1&nbsp; &nbsp; &nbsp; &nbsp; echo "discount quarter 1";&nbsp; &nbsp; }&nbsp; &nbsp; elseif ( $current_time <= $quarter3 ){&nbsp; &nbsp; &nbsp; &nbsp; // quarter 2&nbsp; &nbsp; &nbsp; &nbsp; echo "discount quarter 2";&nbsp; &nbsp; }&nbsp; &nbsp; elseif ( $current_time <= $quarter4){&nbsp; &nbsp; &nbsp; &nbsp; // quarter 3&nbsp; &nbsp; &nbsp; &nbsp; echo "discount quarter 3";&nbsp; &nbsp; }&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; // quarter 4&nbsp; &nbsp; &nbsp; &nbsp; echo "discount quarter 4";&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP