niko craft
niko craft

Reputation: 2977

where should timezone processing be done, on server or on client?

Where do you process timezone calculations, is it better do do it on the server or on the client using a javascript library like moment?

Currently I am doing it on server using this library: https://github.com/camroncade/timezone

and these two:

public function getPublishedAtAttribute()
{
    if(Auth::guest()) {
        return $this->attributes['published_at']->format('Y-m-d\TH:i\Z');
    }
    else {
        $timezone = Auth::user()->timezone;
        if(isset($this->attributes['published_at']))
            return Timezone::convertFromUTC($this->attributes['published_at'], $timezone, 'Y-m-d H:i');
        else
            return null;
    }
}

public function setPublishedAtAttribute($published_at)
{
    if($published_at) {
        $published_at_temp = new Carbon($published_at, Auth::user()->timezone);
        $this->attributes['published_at'] = Timezone::convertToUTC($published_at_temp->addSeconds(59), Auth::user()->timezone);
    }
    elseif(!$this->published_at) {
        $this->attributes['published_at'] = Carbon::now();
    }
}

Are there any minuses for doing it on the server or any pluses doing it on the client?

Which is better approach?

Upvotes: 0

Views: 119

Answers (3)

shukshin.ivan
shukshin.ivan

Reputation: 11340

Store always server time. It is easy to deal with, so you can give an easy opportunity to change timezone (just change one field, not all existing records).

Then convert every time output in view . Create simple timeHelper which is aware of current user and his timezone and inject it in view @inject('timehelper', 'App\Services\Timehelper') and {{ $timehelper->out($model->created_at) }}. In out() just apply user's timezone. Sometimes it is easy to output raw time with server timezone and then convert it via moment.js, using some attribute: <span ts="150...">20:20 20th July</span>

You have to store client's time just in cases like when you have strict billing, based on users' local time.

Upvotes: 2

Nate
Nate

Reputation: 1274

On the client, you have to account for a user taking their laptop with them when they travel to a different timezone. Now there's the server time, the user's local time, and the user's laptop time. And that's before you factor in any latency in a time-sensitive transaction.

Upvotes: 1

WebSon
WebSon

Reputation: 521

Do it on server side. I think it would be more "beautiful"

Upvotes: 0

Related Questions