Using and comparing relative time in Rails - ruby-on-rails

I need to know how to do relative time in rails but not as a sentence, more like something i could do this with (when i input format like this 2008-08-05 23:48:04 -0400)
if time_ago < 1 hour, 3 weeks, 1 day, etc.
execute me
end

Basic relative time:
# If "time_ago" is more than 1 hour past the current time
if time_ago < 1.hour.ago
execute_me
end
Comparison:
Use a < to see if time_ago is older than 1.hour.ago, and > to see if time_ago is more recent than 1.hour.ago
Combining times, and using fractional times:
You can combine times, as davidb mentioned, and do:
(1.day + 3.hours + 2500.seconds).ago
You can also do fractional seconds, like:
0.5.seconds.ago
There is no .milliseconds.ago, so if you need millisecond precision, just break it out into a fractional second. That is, 1 millisecond ago is:
0.001.seconds.ago
.ago() in general:
Putting .ago at the end of just about any number will treat the number as a #of seconds.
You can even use fractions in paranthesis:
(1/2.0).hour.ago # half hour ago
(1/4.0).year.ago # quarter year ago
NOTE: to use fractions, either the numerator or denominator needs to be a floating point number, otherwise Ruby will automatically cast the answer to an integer, and throw off your math.

You mean sth. like this?
if time_ago < Time.now-(1.days+1.hour+1.minute)
execute me
end

Related

Ruby time multiplication

Can some break this down for me? In my mind 5 minutes squared is 25 minutes
irb(main):014:0> now = Time.now.utc
=> 2019-05-03 01:36:41 UTC
irb(main):015:0> now + (5.minutes ** 2)
=> 2019-05-04 02:36:41 UTC
There is no Numeric#minutes in ruby, that’s Rails monkeypatching everything.
Numeric#minutes is delegated to ActiveSupport::Duration#minutes which in turn constructs an ActiveSupport::Duratioon::Scalar instance, with an amount of seconds as a “number behind.” That number will be used in:
coercion that might be used in any arithmetics involving Numeric, amongst others.
That said, when foo.minutes meets the arithmetic operation with a Numeric as a RHO, it [using coercion] does the math using the number of seconds.
Even more, the comparison against Numeric would also work:
5.minutes == 300
#⇒ true
Hence my advise: never ever use these misleading monkeypatched crap. Use seconds explicitly to perform date/time operations.

Comparing times in Rails

I am using this code to compare times:
(time1.to_i - time2.to_i).abs < 5
The intention is that if two times are measured within 5 seconds from each other, they will be equal. I'm using it to compare updating of records, so 5 seconds is acceptable as a buffer, and stops the code returning false when the records are only splitseconds apart.
Is there a better way to do this?
In Ruby, you can subtract two Time objects directly to get the difference in seconds. Rails provides some convenience helpers on integers to convert them into seconds as well:
(time1 - time2).abs < 5.seconds
If you know that time2 always comes after time1, you can get rid of the abs:
time2 - time1 < 5.seconds

Operations on DateTime in rails

Is it possible to subtract one DateTime from another and get the result in Time.
Example if we subtract 2011-08-27 01:00:00 UTC from 2011-08-29 08:13:00 UTC, the result should be 55:13:00 (hope I didn't make a mistake while calulating :p)
Thanks.
Time is generally expressed in seconds when doing math like this, even fractional seconds if you want. A Time represents a specific point in time, which while internally represented as seconds since the January 1, 1970 epoch, is not intended to be a scalar unit like that.
If you have two DateTime objects, you can determine the difference between them like this:
diff = DateTime.parse('2011-08-29 08:13:00 UTC').to_time - DateTime.parse('2011-08-27 01:00:00 UTC').to_time
# => 198780.0
Once you have the number of seconds, the rest is simply a formatting problem:
'%d:%02d:%02d' % [ diff / 3600, (diff / 60) % 60, diff % 60 ]
# => "55:13:00"

How to find if range is contained in an array of ranges?

Example
business_hours['monday'] = [800..1200, 1300..1700]
business_hours['tuesday'] = [900..1100, 1300..1700]
...
I then have a bunch of events which occupy some of these intervals, for example
event = { start_at: somedatetime, end_at: somedatetime }
Iterating over events from a certain date to a certain date, I create another array
busy_hours['monday'] = [800..830, 1400..1415]
...
Now my challenges are
Creating an available_hours array that contains business_hours minus busy_hours
available_hours = business_hours - busy_hours
Given a certain duration say 30 minutes, find which time slots are available in available_hours. In the examples above, such a method would return
available_slots['monday'] = [830..900, 845..915, 900..930, and so on]
Not that it checks available_hours in increments of 15 minutes for slots of specified duration.
Thanks for the help!
I think this is a job for bit fields. Unfortunately this solution will rely on magic numbers, conversions helpers and a fair bit of binary logic, so it won't be pretty. But it will work and be very efficient.
This is how I'd approach the problem:
Atomize your days into reasonable time intervals. I'll follow your example and treat each 15 minute block of time as considered one time chunk (mostly because it keeps the example simple). Then represent your availability per hour as a hex digit.
Example:
0xF = 0x1111 => available for the whole hour.
0xC = 0x1100 => available for the first half of the hour.
String 24 of these together together to represent a day. Or fewer if you can be sure that no events will occur outside of the range. The example continues assuming 24 hours.
From this point on I've split long Hex numbers into words for legibility
Assuming the day goes from 00:00 to 23:59 business_hours['monday'] = 0x0000 0000 FFFF 0FFF F000 0000
To get busy_hours you store events in a similar format, and just & them all together.
Exmample:
event_a = 0x0000 0000 00F0 0000 0000 0000 # 10:00 - 11:00
event_b = 0x0000 0000 0000 07F8 0000 0000 # 13:15 - 15:15
busy_hours = event_a & event_b
From busy_hours and business_hours you can get available hours:
available_hours = business_hours & (busy_hours ^ 0xFFFF FFFF FFFF FFFF FFFF FFFF)
The xor(^) essentialy translates busy_hours into not_busy_hours. Anding (&) not_busy_hours with business_hours gives us the available times for the day.
This scheme also makes it simple to compare available hours for many people.
all_available_hours = person_a_available_hours & person_b_available_hours & person_c_available_hours
Then to find a time slot that fits into available hours. You need to do something like this:
Convert your length of time into a similar hex digit to the an hour where the ones represent all time chunks of that hour the time slot will cover. Next right shift the digit so there's no trailing 0's.
Examples are better than explanations:
0x1 => 15 minutes, 0x3 => half hour, 0x7 => 45 minutes, 0xF => full hour, ... 0xFF => 2 hours, etc.
Once you've done that you do this:
acceptable_times =[]
(0 .. 24 * 4 - (#of time chunks time slot)).each do |i|
acceptable_times.unshift(time_slot_in_hex) if available_hours & (time_slot_in_hex << i) == time_slot_in_hex << i
end
The high end of the range is a bit of a mess. So lets look a bit more at it. We don't want to shift too many times or else we'll could start getting false positives at the early end of the spectrum.
24 * 4 24 hours in the day, with each represented by 4 bits.
- (#of time chunks in time slot) Subtract 1 check for each 15 minutes in the time slot we're looking for. This value can be found by (Math.log(time_slot_in_hex)/Math.log(2)).floor + 1
Which starts at the end of the day, checking each time slot, moving earlier by a time chunk (15 minutes in this example) on each iteration. If the time slot is available it's added to the start of acceptable times. So when the process finishes acceptable_times is sorted in order of occurrence.
The cool thing is this implementation allows for time slots that incorporate so that your attendee can have a busy period in their day that bisects the time slot you're looking for with a break, where they might be otherwise busy.
It's up to you to write helper functions that translate between an array of ranges (ie: [800..1200, 1300..1700]) and the hex representation. The best way to do that is to encapsulate the behaviour in an object and use custom accessor methods. And then use the same objects to represent days, events, busy hours, etc. The only thing that's not built into this scheme is how to schedule events so that they can span the boundary of days.
To answer your question's title, find if a range of arrays contains a range:
ary = [800..1200, 1300..1700]
test = 800..830
p ary.any? {|rng| rng.include?(test.first) and rng.include?(test.last)}
# => true
test = 1245..1330
p ary.any? {|rng| rng.include?(test.first) and rng.include?(test.last)}
# => false
which could be written as
class Range
def include_range?(r)
self.include?(r.first) and self.include?(r.last)
end
end
Okay, I don't have time to write up a full solution, but the problem does not seem too difficult to me. I hacked together the following primitive methods you can use to help in constructing your solution (You may want to subclass Range rather than monkey patching, but this will give you the idea):
class Range
def contains(range)
first <= range.first || last >= range.last
end
def -(range)
out = []
unless range.first <= first && range.last >= last
out << Range.new(first, range.first) if range.first > first
out << Range.new(range.last, last) if range.last < last
end
out
end
end
You can iterate over business hours and find the one that contains the event like so:
event_range = event.start_time..event.end_time
matching_range = business_hours.find{|r| r.contains(event_range)}
You can construct the new array like this (pseudocode, not tested):
available_hours = business_hours.dup
available_hours.delete(matching_range)
available_hours += matching_range - event_range
That should be a pretty reusable approach. Of course you'll need something totally different for the next part of your question, but this is all I have time for :)

ruby on rails int to minutes::seconds::milliseconds

I have this line, which shows the minutes and seconds. But I have to add milliseconds to it as well for greater accuracy. How do I add that in this line, or is there an easier way to get the desired result?
#duration = [cd.ExactDuration/60000000, cd.ExactDuration/1000000 % 60].map{|t| t.to_s.rjust(2, '0') }.join(':'))
The exact duration type is saved in microseconds. So the first converts to microseconds to minutes, the second part is microseconds to seconds. Now I need to add milliseconds.
cd.ExactDuration/1000 % 1000 should do the trick.
Of course you may also want to tweak the formatting, since that's a datum you don't want to right-justify in a 2-wide field;-). I'd suggest sprintf for string-formatting, though I realize its use is not really intuitive unless you come from a C background.

Resources