从 Laravel 中的时间戳获取日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31780852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:06:15  来源:igfitidea点击:

Get date from timestamp in laravel

phplaravel

提问by Sarath TS

How can I get date from "2015-07-31 06:03:21" using Laravel query builder? In normal query using DATE() we can get date easily, but I don't know how to use DATE() in Laravel query builder. Please check my code sample given below and correct me?

如何使用 Laravel 查询构建器从“2015-07-31 06:03:21”获取日期?在使用 DATE() 的普通查询中,我们可以轻松获取日期,但我不知道如何在 Laravel 查询构建器中使用 DATE()。请检查我下面给出的代码示例并纠正我?

Normal Query

普通查询

SELECT DATE('2015-07-31 06:03:21'), customer_id FROM customer_histories

Laravel Query Builder

Laravel 查询生成器

$customerhistory = Customerhistory::where('customer_id', 1)
            ->select('freetext', 'DATE(created_at)')
            ->get();

采纳答案by baao

You can do this with DB::raw(), though if you are only selecting it, why not just take created_at complete? By default, Eloquent will convertthe created_atand updated_atcolumns to instances of Carbonso you can handle it like this in your code:

你可以用 来做到这一点DB::raw(),但如果你只是选择它,为什么不直接使用 created_at 呢?默认情况下,雄辩会转化created_atupdated_at列的情况下,,所以你可以处理像这样在你的代码:

$customerhistory = Customerhistory::where('customer_id', 1)
            ->select('freetext', 'created_at')
            ->get();

dd($customerhistory[0]->created_at->toDateString());

回答by MaGnetas

You can use DB::raw('something')for that. In this case your raw input will be treated as part of actual SQL.

你可以用DB::raw('something')它。在这种情况下,您的原始输入将被视为实际 SQL 的一部分。

This is something you might wanna give a try:

这是您可能想尝试的东西:

$customerhistory = Customerhistory::where('customer_id', 1)
    ->select('freetext', DB::raw('DATE(`created_at`)'))
    ->get();

More details and yet another example cal be found here.

更多细节和另一个示例 cal 可以在这里找到。

Also it looks like you're using eloquent. You might wanna check the mutators section.

此外,您似乎在使用 eloquent。你可能想检查mutators 部分

回答by Y. Joy Ch. Singha

$customerhistory = Customerhistory::where('customer_id', '=', '1')
            ->select('freetext', DB::raw('DATE(`created_at`)'))
            ->get();

Thanks.

谢谢。