Skip to content

Commit 60806fc

Browse files
authored
Fix issue with saving date attribute in wrong timezone, and fix detection of Carbon date objects
1 parent 2dbc066 commit 60806fc

1 file changed

Lines changed: 36 additions & 3 deletions

File tree

src/Traits/DatesTimezoneConversion.php

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace DivineOmega\DatesTimezoneConversion\Traits;
44

55
use Carbon\Carbon;
6+
use DemeterChain\C;
67
use Illuminate\Database\Eloquent\Model;
78
use Illuminate\Support\Facades\Auth;
89

@@ -44,7 +45,16 @@ public function getAttributeValue($key)
4445
*/
4546
public function setAttribute($key, $value)
4647
{
47-
if ($this->isDateObject($key, $value)) {
48+
if (in_array($key, $this->getDates())) {
49+
$value = $this->convertToDateObject($value);
50+
51+
/** @var Model $user */
52+
$user = Auth::user();
53+
54+
if ($user) {
55+
$value = Carbon::parse($value, $user->getAttributeValue('timezone'));
56+
}
57+
4858
$value->setTimezone(config('app.timezone'));
4959
}
5060

@@ -63,7 +73,30 @@ private function isDateObject($key, $value)
6373
{
6474
return in_array($key, $this->getDates()) &&
6575
is_object($value) &&
66-
get_class($value) === Carbon::class;
76+
$value instanceof Carbon;
77+
}
78+
79+
/**
80+
* Converts a value to a Carbon date object if needed.
81+
*
82+
* @param $value
83+
* @return Carbon
84+
*/
85+
private function convertToDateObject($value)
86+
{
87+
if (is_object($value) && $value instanceof Carbon) {
88+
return $value;
89+
}
90+
91+
if (is_string($value)) {
92+
return Carbon::parse($value);
93+
}
94+
95+
if (is_integer($value)) {
96+
return Carbon::createFromTimestamp($value);
97+
}
98+
99+
throw new \Exception('Unable to convert value to Carbon date object.');
67100
}
68101

69-
}
102+
}

0 commit comments

Comments
 (0)