PHP逻辑,与特定日期进行比较

时间:2012-10-26 06:05:11

标签: php date logic switch-statement getdate

我需要编写一个php脚本来确定用户必须支付的金额,具体取决于他们注册的日期。他们注册的越多,他们支付的费用越多,所以这里是脚本的基本代码:

private $date;

function __construct() {
    $this->date = getdate();
}

function get_amount()
{
    $day = $this->date["mday"];
    $month = $this->date["month"];
    $year = $this->date["year"];
    $date = $day.$month.$year;
    switch($date) {
        case "26October2012":
            return "800";
            break;
        case "26Novermber2012":
            return "900";
            break;
    }
}

但显然这个案例陈述不能正常运作。因此,如果用户在2012年10月26日之前注册,那么他们支付800,如果是在11月26日之前但在10月26日之后他们支付900.那么我该如何编码这个逻辑呢?

3 个答案:

答案 0 :(得分:4)

只需将日期转换为Unix时间戳,比较它们,使整个事情变得更加简单。 请参阅 strtotime 功能。

$compare_date = "2012-10-26";
$todays_date = date("Y-m-d");

$today_ts = strtotime($todays_date);//unix timestamp value for today
$compare_ts = strtotime($compare_date);//unix timestamp value for the compare date

if ($today_ts > $compare_ts) {//condition to check which is greater
   //...
}

strtotime 将您的日期时间转换为整数 Unix Timestamp. Unix时间戳定义为自午夜协调世界时(UTC)以来经过的秒数),1970年1月1日。因此,作为一个整数,很容易比较,没有字符串操作。

答案 1 :(得分:0)

您无法使用switch语句进行范围比较。

您可以将日期转换为时间戳,然后使用if-else进行比较。

答案 2 :(得分:0)

为不同的日期创建一个包含amount的数组:

$amountPerDate = array(
    '2012-10-26' => 800,
    '2012-11-26' => 900,
);

循环通过它获得相应的amount值:

krsort($amountPerDate); // Recursive sort to check greater dates first
$date = strtotime($date);  // Convert '2012-10-23' to its numeric equivalent for the date comprasion
$amount = 0; // Default amount value
foreach ($valuePerData as $date => $amount) {
    if ($date >= strtotime($date)) {
        $amount = $amount;
    }
}