我四处寻找,但未能找到以特定格式返回Laravel时间戳/日期时间的明确方法。它如何保存在数据库中对我来说并不重要,但当我提取数据时,我想格式化它,以便可以通过JavaScript进行解析。有人知道一个不需要创建多个访问者的好方法吗?
编辑:为了添加更多细节,我实际上使用的是AngularJS,并希望以一种格式返回日期,以便Angular及其日期过滤器能够理解它。对于当前的格式,日期过滤器不起作用,因为根据我所知,它无法解析日期。
getFooAttribute
方法,其中Foo是要访问的列的大小写为"camel"的名称。因此,您应该为test_date
(或任何其他)属性定义一个访问器。当试图检索test_date
的值时,Eloquent将自动调用访问器。
(在这个例子中,我将在用户模型中定义它)
<?php
namespace App;
use CarbonCarbon;
class User extends Model {
protected $table = 'users';
public function getTestDateAttribute($date) {
//What format do you store in db?
$storedformat = createFromFormat('Y-m-d H:i:s', $date);
//What format would you like to show?
$customformat = $storedformat->format('Y.m.d. H:i:s');
return $customformat;
}
}
然后您将默认看到以下格式:
$user = User::find(1);
$user->test_date; //2015.11.12. 8:50:20
如果您想编写更简单的代码,那么应该使用Traits。
让我们在AppDateTrait.php
文件中定义DateTrait:
<?php
trait DateTrait {
public function getTestDateAttribute($date) {
//What format do you store in db?
$storedformat = createFromFormat('Y-m-d H:i:s', $date);
//What format would you like to show?
$customformat = $storedformat->format('Y.m.d. H:i:s');
return $customformat;
}
}
然后在每个想要格式化test_date
列的模型中使用它。
<?php
namespace App;
use CarbonCarbon;
class User extends Model {
use AppDateTrait;
...
}
在您的视图中,只需执行以下操作:
$variable->created_at->format('m-d-y')
这里的这个页面可能有助于熟悉碳日期以及如何使用和格式化它们。
关于将它们解析为Javascript可以解释的格式,也许你可以这样做——假设它来自一个你已经拉到视图中的有说服力的对象或类似的东西:
{{ (new CarbonCarbon($dataPassedIn->created_at))->format('F d, Y H:ia') }}
这将返回一个类似于September 02, 2015 09:43am
的日期,尽管我不确定解析为javascript所需的确切格式。