Created
October 20, 2016 13:53
-
-
Save tomschlick/ae9d468ad56dbf70e58cf0088cbd14c0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
trait NullableDate | |
{ | |
/** | |
* Transform the date for display, add timezone if available | |
* | |
* @param string $field_name | |
* | |
* @param string $format | |
* | |
* @param string $tz | |
* | |
* @return \Carbon\Carbon | |
*/ | |
public function displayDate(string $field_name, string $format = 'j M Y h:i a', string $tz = null) | |
{ | |
$field = $this->{$field_name}; | |
if (is_null($field)) { | |
return null; | |
} | |
if (! $field instanceof Carbon) { | |
$field = parent::asDateTime($field); | |
} | |
if ($field->lt(Carbon::parse('1000-01-01'))) { | |
return null; | |
} | |
// If the user is logged in, get their timezone | |
if (is_null($tz) && isLoggedIn() && me()) { | |
$tz = me()->getTimezone(); | |
} | |
Carbon::setToStringFormat($format); | |
if ($tz && $tz != 'UTC') { | |
return $field->setTimezone($tz); | |
} | |
return $field; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment