您在哪里处理时区计算,是在服务器上还是在客户端上使用像 moment 这样的 JavaScript 库进行处理更好?
目前我正在使用此库在服务器上执行此操作: https://github.com/camroncade/timezone
还有这两个:
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();
}
}
在服务器上执行此操作有什么缺点或在客户端上执行此操作有任何优点吗?
哪种方法更好?
最佳答案
始终存储服务器时间。它很容易处理,因此您可以轻松更改时区(只需更改一个字段,而不是所有现有记录)。
然后在view中每次输出时进行转换。创建简单timeHelper
它知道当前用户和他的时区并将其注入(inject) View @inject('timehelper', 'App\Services\Timehelper')
和{{ $timehelper->out($model->created_at) }}
。在 out()
只需应用用户的时区。有时很容易输出带有服务器时区的原始时间,然后通过 moment.js
进行转换。 ,使用一些属性:<span ts="150...">20:20 20th July</span>
您必须存储客户的时间,以防万一您根据用户的本地时间进行严格的计费。
关于javascript - 时区处理应该在哪里进行,在服务器上还是在客户端上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45599037/