php 如何将 Laravel Query Builder 中的日期格式从“2016-03-12”更改为“12-Mar-2016”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35909647/
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
How to change date format in laravel Query Builder from "2016-03-12" to "12-Mar-2016"
提问by GRESPL Nagpur
How to change date-format in laravel from "2016-03-12" to "12-Mar-2016"
如何将 Laravel 中的日期格式从“2016-03-12”更改为“12-Mar-2016”
$results = DB::table('customers as cust')
->where('cust.id',$id)
->select("cust.*","cust.cust_dob as dob")
->first();
Should I use laravel raw query.
我应该使用 Laravel 原始查询吗?
I tried this,
我试过这个,
->select("cust.*","DATE_FORMAT(cust.cust_dob, '%d-%M-%Y') as formatted_dob")
Any guide on this please.
请提供任何有关此的指南。
采纳答案by Zamrony P. Juhara
回答by cronLancer
Try to use this:
尝试使用这个:
$results = DB::table('customers as cust')
->where('cust.id',$id)
->select(DB::raw('DATE_FORMAT(cust.cust_dob, "%d-%b-%Y") as formatted_dob')
->first();
回答by GRESPL Nagpur
As there is no way except using raw query, I am using like this. It worked for me.
由于除了使用原始查询之外别无他法,我正在使用这样的方法。它对我有用。
->select("cust.*", DB::raw("DATE_FORMAT(cust.cust_dob, '%d-%b-%Y') as formatted_dob"))
回答by devnull
Laravel gives a opportunity to define accessors/mutators. Which you can use in this case rather than to do it via Queries.
Laravel 提供了定义访问器/修改器的机会。在这种情况下,您可以使用它而不是通过查询来完成。
i would add method in Customer model class
我会在客户模型类中添加方法
public function getCustDobAttribute($value) {
return //Format the value Which represent the value in database;
}
Example:Imagine you want retrieve customer name, You want get it as First charterer capital and the rest small.
示例:假设您想检索客户名称,您希望将其作为第一租船人资本,其余为小。
public function getFirstNameAttribute($value)
{
return ucfirst($value);
}
Reference:
参考:
https://laravel.com/docs/5.1/eloquent-mutators#accessors-and-mutators
https://laravel.com/docs/5.1/eloquent-mutators#accessors-and-mutators
回答by Alexey Mezenin
You can always use Carbon's ->format('m/d/Y');
to change format.
您可以随时使用 Carbon->format('m/d/Y');
来更改格式。
Or you can just use selectRaw
to build your queries.
或者您可以仅用于selectRaw
构建查询。
Also, you can try to use date mutators by settting $dateFormat
to date format you want to use:
https://laravel.com/docs/5.1/eloquent-mutators#date-mutators
此外,您可以通过设置$dateFormat
要使用的日期格式来尝试使用日期修改器:https:
//laravel.com/docs/5.1/eloquent-mutators#date-mutators