Skip to content

Instantly share code, notes, and snippets.

@henrik
Last active July 12, 2019 08:18
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save henrik/945f1147e3def6b7789a to your computer and use it in GitHub Desktop.
Save henrik/945f1147e3def6b7789a to your computer and use it in GitHub Desktop.
Is a given time in a time range, in Ruby?
# 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) }
# 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