Skip to content

Instantly share code, notes, and snippets.

@tomschlick
Created October 20, 2016 13:53
Show Gist options
  • Save tomschlick/ae9d468ad56dbf70e58cf0088cbd14c0 to your computer and use it in GitHub Desktop.
Save tomschlick/ae9d468ad56dbf70e58cf0088cbd14c0 to your computer and use it in GitHub Desktop.
<?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