laravel-timezone icon indicating copy to clipboard operation
laravel-timezone copied to clipboard

Returning Carbon instances when using Model Casting

Open amandiobm opened this issue 4 years ago • 6 comments

Custom Cast - https://laravel.com/docs/8.x/eloquent-mutators#custom-casts

Add a new way to handle user timezone dates.

When used on the Eloquent, it automatically transforms the value into a Carbon instance with the user timezone applied.

amandiobm avatar May 19 '20 21:05 amandiobm

I'm a huge fan of your work here! 😂 Quick look around doens't raise any concern, sounds good! 👍

jpmurray avatar May 19 '20 21:05 jpmurray

@jamesmills any idea if you want to merge this or not ?

jpmurray avatar Aug 18 '20 15:08 jpmurray

Sorry, late to the party @jpmurray

I do like the look of this.

Forgive me, I've been out of the Laravel world for a while. Is the addition of this going to break the default usage or is it just an added optional feature? I cannot remember what the Casts thing actually does but my initial thinking is it's just an added additional feature that can be used or ignored?

Also love the trait TimezoneTrait -> protected function getUserTimezone refactor @amandiobm ;-)

Let's get this in!

jamesmills avatar Feb 18 '21 07:02 jamesmills

Updated the description.

amandiobm avatar Feb 19 '21 00:02 amandiobm

So this would remove all the need for us to format the date/time because it would just be an instance of Carbon with the correct timezone set. I love this. Maybe what I should have done with the main package....

jamesmills avatar Feb 21 '21 03:02 jamesmills

I think there may be an issue with the logic here. When using the cast on the updated at attribute, the set function is called through touch() which creates a new Carbon object via ::now(). This object will have the current timezone of your app, or server, rather than the local timezone. This current object/timezone will then be passed through the convertFromLocal method which will re-parse that object as your local timezone and convert it again to UTC.

The end result is, if for example you are currently UTC+1 (UK daylight savings) but your server is configured for UTC, if you perform an action at 10:30am, the touch timestamp will be 9:30am, and after convert from local it will be recorded at 8:30am.

As far as I can tell, the set function doesn't provide enough info to determine if it was real local timezone, or one of these server generated ones.

jedjones-uk avatar May 02 '21 00:05 jedjones-uk