From bc3c7852838324c633ebaff20d2bc3bc9196e404 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=2E=20Nagy=20Gerg=C5=91?= Date: Wed, 27 Mar 2024 19:11:38 +0100 Subject: [PATCH] fix date handling --- src/Fields/Date.php | 57 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 53 insertions(+), 4 deletions(-) diff --git a/src/Fields/Date.php b/src/Fields/Date.php index 52c7f0d2..5f87eadf 100644 --- a/src/Fields/Date.php +++ b/src/Fields/Date.php @@ -4,8 +4,10 @@ use Closure; use DateTimeInterface; +use DateTimeZone; use Illuminate\Database\Eloquent\Model; use Illuminate\Http\Request; +use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Date as DateFactory; class Date extends Field @@ -18,13 +20,18 @@ class Date extends Field /** * The timezone. */ - protected string $timezone = 'UTC'; + protected string $timezone; /** * Indicates if the field should include time. */ protected bool $withTime = false; + /** + * The default timezone. + */ + protected static ?string $defaultTimezone = null; + /** * Create a new field instance. */ @@ -34,6 +41,15 @@ public function __construct(string $label, Closure|string|null $modelAttribute = $this->type('date'); $this->step(1); + $this->timezone(static::$defaultTimezone ?: Config::get('app.timezone')); + } + + /** + * Set the default timezone. + */ + public static function defaultTimezone(string|DateTimeZone $value): void + { + static::$defaultTimezone = $value instanceof DateTimeZone ? $value->getName() : $value; } /** @@ -77,13 +93,46 @@ public function withTime(bool $value = true): static /** * Set the timezone. */ - public function timezone(string $value): static + public function timezone(string|DateTimeZone $value): static { - $this->timezone = $value; + $this->timezone = $value instanceof DateTimeZone ? $value->getName() : $value; + + $this->suffix($this->timezone); return $this; } + /** + * {@inheritdoc} + */ + public function getValueForHydrate(Request $request): ?string + { + $value = parent::getValueForHydrate($request); + + if (! is_null($value)) { + $value = DateFactory::parse($value, $this->timezone) + ->setTimezone(Config::get('app.timezone')) + ->toISOString(); + } + + return $value; + } + + /** + * {@inheritdoc} + */ + public function getValue(Model $model): mixed + { + $value = parent::getValue($model); + + if (! is_null($value)) { + $value = DateFactory::parse($value, Config::get('app.timezone')) + ->setTimezone($this->timezone); + } + + return $value; + } + /** * {@inheritdoc} */ @@ -91,7 +140,7 @@ public function resolveFormat(Request $request, Model $model): ?string { if (is_null($this->formatResolver)) { $this->formatResolver = function (Request $request, Model $model, mixed $value): ?string { - return is_null($value) ? $value : DateFactory::parse($value)->setTimezone($this->timezone)->format($this->format); + return is_null($value) ? $value : $value->format($this->format); }; }