Skip to content

Instantly share code, notes, and snippets.

@citrus
Created July 26, 2011 20:28
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save citrus/1107932 to your computer and use it in GitHub Desktop.
Save citrus/1107932 to your computer and use it in GitHub Desktop.
Round time to next quarter hour with ruby (00,15,30,45)
module DateTimeHelper
def time_to_next_quarter_hour(time)
array = time.to_a
quarter = ((array[1] % 60) / 15.0).ceil
array[1] = (quarter * 15) % 60
Time.local(*array) + (quarter == 4 ? 3600 : 0)
end
end
require 'test/unit'
class DateTimeHelperTest < Test::Unit::TestCase
include DateTimeHelper
def run_against(hour, minute)
time = Time.local(2011, 1, 1, hour, minute)
time_to_next_quarter_hour(time).strftime('%I:%M %p').gsub(/^0/, '')
end
def test_midnight
assert_equal '12:00 AM', run_against(00, 00)
end
def test_on_first_quarter
assert_equal '12:00 PM', run_against(12, 00)
end
def test_in_first_quarter
assert_equal '12:15 PM', run_against(12, 01)
assert_equal '12:15 PM', run_against(12, 07)
assert_equal '12:15 PM', run_against(12, 14)
end
def test_on_second_quarter
assert_equal '12:15 PM', run_against(12, 15)
end
def test_in_second_quarter
assert_equal '12:30 PM', run_against(12, 16)
assert_equal '12:30 PM', run_against(12, 22)
assert_equal '12:30 PM', run_against(12, 29)
end
def test_on_third_quarter
assert_equal '12:30 PM', run_against(12, 30)
end
def test_in_third_quarter
assert_equal '12:45 PM', run_against(12, 31)
assert_equal '12:45 PM', run_against(12, 37)
assert_equal '12:45 PM', run_against(12, 44)
end
def test_on_fourth_quarter
assert_equal '12:45 PM', run_against(12, 45)
end
def test_in_fourth_quarter
assert_equal '1:00 PM', run_against(12, 46)
assert_equal '1:00 PM', run_against(12, 52)
assert_equal '1:00 PM', run_against(12, 59)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment