Last active
July 12, 2019 08:18
-
-
Save henrik/945f1147e3def6b7789a to your computer and use it in GitHub Desktop.
Is a given time in a time range, in Ruby?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Note: upper bound is 12:01:59 (you could use second precision to get around this, e.g. "12:01:00") | |
time = Time.mktime(2014, 10, 14, 12, 1) | |
allowed_ranges = [ | |
"11:59".."12:01", | |
] | |
formatted_time = time.strftime("%H:%M") | |
p allowed_ranges.any? { |range| range.cover?(formatted_time) } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Note: upper bound is 12:01:00 | |
require "active_support/core_ext/time/calculations" | |
time = Time.mktime(2014, 10, 14, 12, 1) | |
allowed_ranges = [ | |
"11:59".."12:01", | |
] | |
p allowed_ranges.any? { |range| | |
h, m = range.first.split(":") | |
from = time.change(hour: h, min: m) | |
h, m = range.last.split(":") | |
unto = time.change(hour: h, min: m) | |
(from..unto).cover?(time) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment