如何获取在给定时区中特定日期开始一天的 Ruby Time 对象。
如何获取在给定时区中特定日期开始一天的 Ruby Time 对象。
date = Date.today
date.to_time.in_time_zone('America/New_York').beginning_of_day
当前输出 => 2011年11月2日00:00:00 -0400
Time.now.in_time_zone('Asia/Shanghai').beginning_of_day
当前输出为 => 2011年11月3日 00:00:00 +0800
date = Date.today
date.to_time.in_time_zone('Asia/Shanghai').beginning_of_day
目前的输出为 => 2011-11-02 00:00:00 +0800
date.to_time.in_time_zone('时区').beginning_of_day
会为原始指定日期提供00:00:00 UTC。 - Timothy Hunkeledate.to_time.in_time_zone('Asia/Shanghai').midnight.in_time_zone(Time.zone).midnight #=> 过去一天。
理想情况下,Ruby应该允许我像这样做。date.to_time(zone)
。 - Blake Taylor我最终使用了ActiveSupport::TimeZone
对象上的#local
方法,传递了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)
不确定这是否有帮助,但这让我知道我的Google API配额何时重置:
# The most recent midnight in California in UTC time
def last_california_midnight
(Time.now.utc - 7.hours).midnight + 7.hours
end
def api_calls_today
Call.where(updated_at: { '$gte' => last_california_midnight }).count
end
1/2/2021
(天:1,月份:2,年份:2021)。("1/2/2021").to_time.in_time_zone('Asia/Shanghai').beginning_of_day
#=> Mon, 01 Feb 2021 00:00:00.000000000 CST +08:00
Time.zone = 'Asia/Shanghai'
Time.current.beginning_of_day
#=> Mon, 12 Jul 2021 00:00:00.000000000 CST +08:00
我总是参考时间而不是日期,因为从一开始就可以确保我得到了所需时区的正确输出。
请注意,这两种方式都提供相同格式的结果。因此,您可以在进一步的时间差计算中使用它。
当定义时区时,我更喜欢使用Time.current
而不是Time.now
,这可以确保时间处于您想要的时区。无论如何,在使用之前,请始终在Rails Console中检查结果。