从 UTC 获取按本地时区过滤的数据

Get data filtering by local timezone from UTC

我们在 Laravel 5.2 有一个应用程序。在我们的数据库中,published_at 将日期存储在时间戳中,碳实例采用 UTC 格式,就像 created_at 和 updated_at.

每个 post 都应该在每个时区的午夜发布。我们以 UTC 格式保存日期数据,例如

'published_at' => '2016-04-12 00:00:00'

我们想做的就是这样;

如果美国的人查看它,那么 he/she 会在 his/her 午夜后看到 post。如果中国人查看它,那么 he/she 会在 his/her 午夜后看到 post。我们怎样才能做到这一点?

这就是我们目前正在做的事情。但是,我们认为它不会起作用。

    public function all($limit, array $data = [])
    {
        $posts = $this->post->with('categories')
            ->where(
                'published_at', Carbon::now()->setTimezone($data['user_timezone'])
                                             ->format('Y-m-d 00:00:00')
            )
            ->orderBy('published_at', 'ASC')
            ->paginate($limit);
    }

这是我们第一次在时区工作,我们不知道。任何帮助将不胜感激。谢谢。

听起来您正在尝试做一个 "sequential timezone publish",在 24 小时的过程中,某处是午夜。

假设您已经从某个地方(在 $data? 中)的输入中获取了时区,您可以使用标准的 Eloquent / Laravel 查询生成器措辞来构建您需要的查询:

https://laravel.com/api/master/Illuminate/Database/Query/Builder.html

    public function all($limit, array $data = [])
    {
        $posts = $this->post->with('categories')
            ->where(
                'published_at',
                '<',
                Carbon::now($data['user_timezone'])
                    ->format('Y-m-d H:i:s')
            )
            ->orderBy('published_at', 'ASC')
            ->paginate($limit);
    }

这样,一旦经过的时区出现 "midnight","published_at" 的值就会是 "less than" 当前时间戳,并将其包含在结果中。