Skip to content

Commit

Permalink
fix date handling
Browse files Browse the repository at this point in the history
  • Loading branch information
iamgergo committed Mar 27, 2024
1 parent f43c2f7 commit bc3c785
Showing 1 changed file with 53 additions and 4 deletions.
57 changes: 53 additions & 4 deletions src/Fields/Date.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
*/
Expand All @@ -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;
}

/**
Expand Down Expand Up @@ -77,21 +93,54 @@ 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}
*/
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);
};
}

Expand Down

0 comments on commit bc3c785

Please sign in to comment.