Skip to content

Instantly share code, notes, and snippets.

@danielstgt
Created May 13, 2020 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielstgt/ae0c5b157081f832e1b58f34f2fbf4d7 to your computer and use it in GitHub Desktop.
Save danielstgt/ae0c5b157081f832e1b58f34f2fbf4d7 to your computer and use it in GitHub Desktop.
Eloquent DateTime Formatted Trait (Example for Germany)
<?php
namespace App\Traits;
trait FormattedDate
{
public function initializeFormattedDate()
{
$this->append('formatted_created_at');
$this->append('formatted_created_at_date');
$this->append('formatted_created_at_time');
$this->append('formatted_updated_at');
$this->append('formatted_updated_at_date');
$this->append('formatted_updated_at_time');
}
// created_at
public function getFormattedCreatedAtAttribute()
{
return $this->created_at->format('d.m.Y H:i'); // e.g. 13.04.2020 19:33
}
public function getFormattedCreatedAtDateAttribute()
{
return $this->created_at->format('d.m.Y'); // e.g. 13.04.2020
}
public function getFormattedCreatedAtTimeAttribute()
{
return $this->created_at->format('H:i'); // e.g. 19:33
}
// updated_at
public function getFormattedUpdatedAtAttribute()
{
return $this->updated_at->format('d.m.Y H:i'); // e.g. 13.04.2020 19:33
}
public function getFormattedUpdatedAtDateAttribute()
{
return $this->updated_at->format('d.m.Y'); // e.g. 13.04.2020
}
public function getFormattedUpdatedAtTimeAttribute()
{
return $this->updated_at->format('H:i'); // e.g. 19:33
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment