Get Time Object at Start of Day in a Particular Time Zone

孤人 提交于 2019-12-20 10:29:07

问题


How can I get a ruby Time object that represents the start of the day on a particular date in a given timezone.


回答1:


date = Date.today

date.to_time.in_time_zone('America/New_York').beginning_of_day

Currently outputs => 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

date = Date.today

date.to_time.in_time_zone('Asia/Shanghai').beginning_of_day

Currently outputs => 2011-11-02 00:00:00 +0800




回答2:


I ended up using the #local method on the ActiveSupport::TimeZone object passing components of the Date object.

# 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)



回答3:


Not sure if this helps, but this gets me the time at which my Google API quotas reset:

# 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:

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.



来源:https://stackoverflow.com/questions/7988717/get-time-object-at-start-of-day-in-a-particular-time-zone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!