diff --git a/README.md b/README.md index d23dc0d..6b2b2e1 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,102 @@ And with custom formatting // 2018-07-04 3:32 New York, America ``` +### Using models casting class + +#### Basic usage + +``` + Timezone::class, + ]; +} +``` + +#### Advanced usage + +##### Custom format + +``` + Timezone::class.':Y-m-d H:i:s', + ]; +} +``` + +##### Return the timezone as a string passing along the format. + +``` + Timezone::class.':d/m/Y H:i:s,true', + ]; +} +``` + +##### Return the timezone as a string using the default format. + +``` + Timezone::class.':null,true', + ]; +} +``` + ### Saving the users input to the database in UTC This will take a date/time, set it to the users timezone then return it as UTC in a Carbon instance. diff --git a/src/Casts/Timezone.php b/src/Casts/Timezone.php new file mode 100644 index 0000000..fe09157 --- /dev/null +++ b/src/Casts/Timezone.php @@ -0,0 +1,59 @@ +format = $format === 'null' ? null : $format; + $this->showTimezone = filter_var($showTimezone, FILTER_VALIDATE_BOOLEAN); + } + + /** + * Cast the given value. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @param mixed $value + * @param array $attributes + * @return array + */ + public function get($model, $key, $value, $attributes) + { + return TimezoneFacade::convertToLocal(Carbon::parse($value), $this->format, $this->showTimezone); + } + + /** + * Prepare the given value for storage. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @param array $value + * @param array $attributes + * @return string + */ + public function set($model, $key, $value, $attributes) + { + return TimezoneFacade::convertFromLocal($value); + } +}