2016-06-13 25 views
2

我們在Laravel 5.2中有一個應用程序。在我們的數據庫中,published_at使用UTC中的碳實例在timestamp中存儲日期,就像created_at和updated_at一樣。從UTC當地時區獲取數據篩選

每篇文章都應該在每個時區午夜發表。我們將日期數據以UTC格式保存,如

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

我們想要做的就像是;

如果有人在美國觀看它,那麼他/她在他/她的午夜時間之後看到該帖子。如果在中國的人看到它,那麼他/她在他/她的午夜時間之後看到該帖子。我們怎樣才能做到這一點?

這就是我們目前正在做的。但是,我們認爲這不會奏效。

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); 
    } 

這是我們第一次在時區工作,我們不知道。任何幫助將不勝感激。謝謝。

回答

2

聽起來好像你正在嘗試做一個「連續時區發佈」,在24小時的過程中,它是某個地方的午夜。

假設你已經抓住了從輸入某個地方的時區(在$data?),你可以使用標準的雄辯/ 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); 
    } 

這樣,只要在經過的時區發生「午夜」,"published_at"將具有「小於」當前時間戳的值,並將其包括在結果中。

+0

更多信息和文檔:http://carbon.nesbot.com/docs/ –

+0

太好了。這就是我們正在尋找的。謝謝。另外,當我們試圖獲得今天的帖子時,我們用whereBetween()子句替換where()子句部分,如 'whereBetween('published_at',array(Carbon :: now($ data ['timezone'] ) - > format('Ymd 00:00:00'),Carbon :: now($ data ['timezone']) - > format('Ymd H:i:s')))'。這會工作嗎? – IamGhale

+0

@IamGhale你可以將它縮短爲'whereBetween('published_at',[Carbon :: now($ data ['timezone']),Carbon :: tomorrow($ data ['timezone'])])' –