如果金额变为负数,则回显日期0

时间:2016-06-06 02:16:07

标签: php function datetime date-difference

我有以下功能

function get_designment_info_by_id($id) {
    $this->db->where('designment_id', $id);
    $designment_info = $this->db->get('designments')->row_array();
    $designment_info['image'] = self::get_image_for_designment($id);
    $designment_info['count_joined'] = self::get_users_count_joined_by_id($id);
    $designment_info['count_ideas'] = self::get_users_count_ideas_by_id($id);
    $date_to = $designment_info['date_to'];
        $diff = $date_to - now();
        $days = round($diff / 86400);
        $time_left = $days . ' days';



        $designment_info['time_left'] = $time_left;
    return $designment_info;
}

现在在视图中,如果日期已过,它将显示日期已过去的天数。例如,如果截止日期为02-06-16,它将显示'-4天'如何更改函数,如果截止日期已过,它将仅回显零'0'。

3 个答案:

答案 0 :(得分:0)

在分配之前检查它是否为否定,如果是,则将其归零。

$days = round($diff / 86400);
if ($days < 0) $days = 0;
$time_left = $days . ' days';

答案 1 :(得分:0)

只需添加if条件

function get_designment_info_by_id($id) {
    $this->db->where('designment_id', $id);
    $designment_info = $this->db->get('designments')->row_array();
    $designment_info['image'] = self::get_image_for_designment($id);
    $designment_info['count_joined'] = self::get_users_count_joined_by_id($id);
    $designment_info['count_ideas'] = self::get_users_count_ideas_by_id($id);
    $date_to = $designment_info['date_to'];
    $diff = $date_to - now();
    $days = round($diff / 86400);
    // Add this
    if($days < 0){
        $days = 0;
    }
    $time_left = $days . ' days';



    $designment_info['time_left'] = $time_left;
    return $designment_info;
}

答案 2 :(得分:0)

每当使用幻数 86400操纵日期时间时,通常存在不必要的DST干扰风险。为了完全避免这种情况,我使用DateTime编写了一个流程而没有利用86400

// assumes $designment_info['date_to'] is formatted d-m-y from question
$date_to=DateTime::createFromFormat('d-m-y',$designment_info['date_to']);
$date_now=new DateTime("now");
if($date_to<=$date_now){
    echo "0 days"; // not yet passed
}else{
    $passed=$date_to->diff($date_now)->days;
    echo "$passed day",($passed>1?"s":"");  // add plural when needed
}

以下online demo显示$date_to$date_now之前,等同和之后g++ -fPIC -shared a.c -o liba.so 。 (无论如何今天......)