【问题标题】:Why is it that my input box shows Dec. 31, 1969?为什么我的输入框显示的是 1969 年 12 月 31 日?
【发布时间】:2016-11-01 07:57:25
【问题描述】:

它应该是空白的。我怎样才能防止这种情况发生? 我正在使用此代码显示日期

public function bookedOn($chalet_id) {
        $chalet = \App\Chalet::where('chalet_id', '=', $chalet_id)->get();
        if ($chalet->count() > 0) {
            $books = \App\EventBookings::where('chalet_id', '=', $chalet[0]->chalet_id)->value('created_at');
            $str = date('M. d, Y',strtotime($books));
            return $str;
        } else {
            return false;
        }
    }

我认为我需要在这里做一些事情:

$str = date('M.d, Y',strtotime($books));

【问题讨论】:

    标签: php


    【解决方案1】:

    如果您返回 false,则默认日期为 1969 年 12 月 31 日。我的意思是,如果您没有找到任何 $chalet 价值。您可以通过返回默认日期来避免它,或者您可以检查返回的 false 值并将空日期或默认日期放在您的视图中。

    如果它不能解决您的问题,请检查 $book 是否为空。

    更新

    感谢您的夸奖。还有一些想法,你不能删除 else 部分。因为如果您的条件不满足,则不会返回任何内容。所以你什么也得不到。为此,您可以在此处返回当前日期 date('M.d, Y')(不确定它是否与您的功能匹配)。最好设置当前日期而不是使用默认日期。所以你的代码可能是这样的

    public function bookedOn($chalet_id) {
        $chalet = \App\Chalet::where('chalet_id', '=', $chalet_id)->get();
        if ($chalet->count() > 0) {
            $books = \App\EventBookings::where('chalet_id', '=',  $chalet[0]->chalet_id)->value('created_at');
    
            if(!empty($books)){
                $str = date('M. d, Y',strtotime($books));
            }else{
                $str = date('M. d, Y');
            }
    
            return $str;
        } else {
            return date('M. d, Y');
        }
    }
    

    【讨论】:

    • 我删除了“else { return false; }。结果相同 1969 年 12 月 31 日我不想要默认日期或空日期。我需要显示空白。可能是占位符。谢谢您的回复顺便说一句
    【解决方案2】:

    试试这样:

    public function bookedOn($chalet_id) {
        $chalet = \App\Chalet::where('chalet_id', '=', $chalet_id)->get();
        if ($chalet->count() > 0) {
            $books = \App\EventBookings::where('chalet_id', '=', $chalet[0]->chalet_id)->value('created_at');
            if ($books == '') {
                // some default date
                $books = '2010-01-01';
            }
            $str = date('M. d, Y',strtotime($books));
            return $str;
        } else {
            return false;
        }
    }
    

    【讨论】:

    • 嘿@yevgenity 你的回答很有帮助。而不是 $books = '2010-01-01'; 我只是让它 return $books 以某种方式对我有用。
    猜你喜欢
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多