简体   繁体   English

Laravel 5 / Carbon:计算不同时区中特定范围的记录数

[英]Laravel 5 / Carbon: Count number of records for specific range in a different timezone

I store my records in EST timezone rather than UTC as I almost never need to use UTC. 我将记录存储在EST时区而不是UTC,因为我几乎不需要使用UTC。 Recently though I have needed to generate a report in UTC. 尽管最近我需要使用UTC生成报告。

I count the number of "clicks" on my site, this is how I grab yesterdays click total: Click::where('created_at', '>=', Carbon::now()->yesterday())->where('created_at', '<=', Carbon::now()->startOfDay())->count(); 我计算了我网站上的“点击”次数,这就是我昨天获得的点击总数的方法: Click::where('created_at', '>=', Carbon::now()->yesterday())->where('created_at', '<=', Carbon::now()->startOfDay())->count();

That works great, but now I need to get the click total for "yesterday in UTC" -- is there an easy way to do this using eloquent / carbon? 效果很好,但是现在我需要获取“ UTC昨天”的点击总数-是否有一种简单的方法可以使用雄辩的/碳的方法来做到这一点?

Assuming that your records in your database are stored as EST as you mention then you will need to do the following. 假设您提到的数据库中的记录存储为EST,那么您将需要执行以下操作。

// Get the start and end times you want in UTC
$start = Carbon::yesterday('UTC');
$end = Carbon::yesterday('UTC')->endOfDay();

// Convert those times to EST
$start->timezone('EST');
$end->timezone('EST');

// Now query the number of clicks, 'whereBetween' is a great little shortcut 
// for querying over a range
Click::whereBetween('created_at', [$start, $end])->count();

Note that carbon is a fluent API so you could simplify this to; 请注意,碳是一种流畅的API,因此您可以将其简化为:

$start = Carbon::yesterday('UTC')->timezone('EST');
$end = Carbon::yesterday('UTC')->endOfDay()->timezone('EST');

Depends entirely how you want your code to read. 完全取决于您希望代码如何阅读。

As an aside the Carbon::now() and Carbon::yesterday() builders will use the default timezone specified in your php.ini if it is not supplied. 顺便说一句, Carbon::now()Carbon::yesterday()构建器将使用php.ini中指定的默认时区(如果未提供)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM