Given a DateTime, how do I get a range of times with the same date in a particular time zone?

I have a DateTime object representing a specific date, as in "2011-01-15 00:00:00 UTC" for presentation on January 15th. I would like to create a range of times in a specific time zone that has the same date.

The signature of the method is likely to be similar to

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 the same as 2011-01-15 00:00:00 -0600 .. 2011-01-15 23:59:59 -0600 .

+4
source share
2 answers

Can you take an input line instead of an object? If you pass in a DateTime object, then its counter counter is intuitive, because the presentation time of the object is not the actual time you are looking for. This will meet my expectations if you either pass in the correct, absolute DateTime, or in the string itself. The actual meat of the problem is fully handled by ActiveSupport, which I think you are using since you flagged this question with Rails. What does it look like?

 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 

Take 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 
+2
source

What 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)> 
0
source

Source: https://habr.com/ru/post/1334963/


All Articles