Ruby-on-rails 在特定时区的一天开始时获取时间对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7988717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Time Object at Start of Day in a Particular Time Zone
提问by Blake Taylor
How can I get a ruby Time object that represents the start of the day on a particular date in a given timezone.
如何获得代表给定时区中特定日期的一天开始的 ruby Time 对象。
采纳答案by Blake Taylor
I ended up using the #localmethod on the ActiveSupport::TimeZoneobject passing components of the Dateobject.
我最终#local在ActiveSupport::TimeZone传递对象组件的Date对象上使用了该方法。
# Get example date and time zone...
date = Date.today
timezone = ActiveSupport::TimeZone['America/New_York']
# Get beginning of day for date in timezone
timezone.local(date.year, date.month, date.day)
回答by Timothy Hunkele
date = Date.today
date.to_time.in_time_zone('America/New_York').beginning_of_day
Currently outputs => 2011-11-02 00:00:00 -0400
当前输出 => 2011-11-02 00:00:00 -0400
Time.now.in_time_zone('Asia/Shanghai').beginning_of_day
Currently outputs => 2011-11-03 00:00:00 +0800
当前输出 => 2011-11-03 00:00:00 +0800
date = Date.today
date.to_time.in_time_zone('Asia/Shanghai').beginning_of_day
Currently outputs => 2011-11-02 00:00:00 +0800
当前输出 => 2011-11-02 00:00:00 +0800
回答by David J.
Not sure if this helps, but this gets me the time at which my Google API quotas reset:
不确定这是否有帮助,但这让我知道我的 Google API 配额重置的时间:
# The most recent midnight in California in UTC time
def last_california_midnight
(Time.now.utc - 7.hours).midnight + 7.hours
end
I use it like this with Mongoid, for example:
我像这样在 Mongoid 中使用它,例如:
def api_calls_today
Call.where(updated_at: { '$gte' => last_california_midnight }).count
end
This will work no matter what timezone the code is deployed to, as long Mongo is set to UTC.
无论代码部署到哪个时区,只要 Mongo 设置为 UTC,这都将起作用。

