The Carbon package (https://carbon.nesbot.com/) takes PHP’s DateTime class to a new level for really accurate date formatting. I created a simple trait that I can drop in a class (note that it requires PHP 7.1):
namespace Vendor; use Carbon\Carbon; trait DateHelper { protected $tz = 'America/New_York'; protected $dateFormat = 'm_d_Y'; /** * @return Carbon */ public function getCarbonDate() : Carbon { return Carbon::now( $this->tz ); } /** * @return string */ public function getFormattedDate( $format = 'm_d_Y' ) : string { return Carbon::now( $this->tz )->format( $format ); } /** * @param string $dateFormat */ public function setDateFormat( string $dateFormat ) { $this->dateFormat = $dateFormat; return $this; } /** * @return string */ public function getDateFormat() : string { return $this->dateFormat; } /** * @param string $tz */ public function setTz( string $tz ) { $this->tz = $tz; return $this; } /** * @return string */ public function getTz() : string { return $this->tz; } }
It’s setup with fluent setters so you can override the defaults when necessary:
class SomeClass { use Vendor\DateHelper; public function getDate() { return $this->setTz('SomeCity/SomeState')->getFormattedDate('m/d/y h:i'); } } $someInstance = new SomeClass(); echo $someInstance->getDate();