Skip to content

Instantly share code, notes, and snippets.

@andrewshell
Last active August 29, 2015 14:20
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 andrewshell/76442d5ee5e1ed557227 to your computer and use it in GitHub Desktop.
Save andrewshell/76442d5ee5e1ed557227 to your computer and use it in GitHub Desktop.
Laravel UTC Model
<?php namespace App\Database;
use Config;
use DateTime;
use DateTimeZone;
use Illuminate\Database\Eloquent\Model;
/**
* Always store DateTime in database as UTC
*/
abstract class UtcModel extends Model
{
public function getTimezone()
{
return Config::get('app.timezone', 'UTC');
}
/**
* Convert a DateTime to a storable string.
*
* @param \DateTime|int $value
* @return string
*/
public function fromDateTime($value)
{
if ($value instanceof DateTime) {
$value = clone $value;
$value->setTimezone(new DateTimeZone('UTC'));
}
return parent::fromDateTime($value);
}
/**
* Return a timestamp as DateTime object.
*
* @param mixed $value
* @return \Carbon\Carbon
*/
protected function asDateTime($value)
{
$default = date_default_timezone_get();
date_default_timezone_set('UTC');
$result = parent::asDateTime($value);
$result->setTimezone(new DateTimeZone($this->getTimezone()));
date_default_timezone_set($default);
return $result;
}
}
@andrewshell
Copy link
Author

If you extend this class instead of Illuminate\Database\Eloquent\Model it will automatically convert DateTime (or Carbon/Carbon) objects to UTC before saving and convert from UTC to the configured app.timezone when fetching DateTime fields from the database.

You can also overwrite the getTimezone function to choose a different timezone from app.timezone for instance based on the current users timezone or from another field in the model.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment