[英]Given a DateTime, how do I get the range of times with the same date in a particular time zone?
I have a DateTime object representing a particular date, as in "2011-01-15 00:00:00 UTC" to represent January 15th. 我有一个代表特定日期的DateTime对象,如“ 2011-01-15 00:00:00 UTC”代表1月15日。 I would like to produce the range of times in a particular time zone that have the same date.
我想产生一个具有相同日期的特定时区的时间范围。
The method signature would probably be something like 方法签名可能类似于
def day_range_for(date, tz)
# ...
end
For example, if I have range_for(DateTime.parse('2011-01-15'), 'CST')
, then I want the result to be a range like 2011-01-15 00:00:00 -0600 .. 2011-01-15 23:59:59 -0600
. 例如,如果我具有
range_for(DateTime.parse('2011-01-15'), 'CST')
,则我希望结果为类似2011-01-15 00:00:00 -0600 .. 2011-01-15 23:59:59 -0600
的范围2011-01-15 00:00:00 -0600 .. 2011-01-15 23:59:59 -0600
。
Can you take the input string instead of the object? 您可以使用输入字符串代替对象吗? If you pass in a DateTime object, its a tad counter intuitive because the time the object represents isn't the actual time you are looking for.
如果传递DateTime对象,则它的提示计数器很直观,因为该对象表示的时间不是您要查找的实际时间。 It would conform to my expectations if you either passed in the correct, absolute DateTime, or the string itself.
如果您传入了正确的绝对DateTime或字符串本身,它将符合我的期望。 The actual meat of the problem is entirely handled by ActiveSupport, which I think you are using since you tagged this question with Rails.
该问题的实际原因完全由ActiveSupport处理,我认为您正在使用它,因为您已用Rails标记了此问题。 How does this look?
看起来如何?
def range_for(input, tz=nil)
if tz.is_a?(String)
tz = ActiveSupport::TimeZone.new(tz)
else
tz = Time.zone
end
if input.acts_like?(:date) || input.acts_like?(:time)
d = input.in_time_zone(tz)
else
d = tz.parse(input)
end
return d.beginning_of_day..d.end_of_day
end
Have a look: 看一看:
ruby-1.9.2-p0 > range_for('2011-01-15', 'Alaska')
=> Sat, 15 Jan 2011 00:00:00 AKST -09:00..Sat, 15 Jan 2011 23:59:59 AKST -09:00
ruby-1.9.2-p0 > range_for(Time.zone.now)
=> Mon, 10 Jan 2011 00:00:00 EST -05:00..Mon, 10 Jan 2011 23:59:59 EST -05:00
ruby-1.9.2-p0 > range_for('2011-01-15', 'EST')
=> Sat, 15 Jan 2011 00:00:00 EST -05:00..Sat, 15 Jan 2011 23:59:59 EST -05:00
How about: 怎么样:
def day_range_for date, zone
(DateTime.new(date.year,date.month,date.day,0,0,0,zone)..DateTime.new(date.year,date.month,date.day,23,59,59,zone))
end
day_range_for(DateTime.parse('2011-01-15'), 'CST')
#=> #<DateTime: 2011-01-15T00:00:00-06:00 (9822307/4,-1/4,2299161)>..#<DateTime: 2011-01-15T23:59:59-06:00 (212161917599/86400,-1/4,2299161)>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.