javascript - 时区处理应该在哪里进行,在服务器上还是在客户端上?

标签 javascript php laravel

您在哪里处理时区计算,是在服务器上还是在客户端上使用像 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/

相关文章:

javascript - 如何自定义网络通知?

php - 尝试使用 php 从数据库特定列值中选择

php - 使用 jQuery 自动 PHP 通知

php - laravel Eloquent 搜索查询

javascript - 在 Win7 上,我如何在旧版本的 IE 中进行调试

javascript - 在 jquery 中的唯一 tabindex 上添加类

php - 导入 Excel 文件时更新重复条目 - php mysql

php - 在 Laravel 查询生成器中保留别名

laravel - 如何在 Laravel Blade 模板中查找字符串

javascript - 如何在本地存储中创建和存储进度条的值