Created
July 26, 2011 20:28
-
-
Save citrus/1107932 to your computer and use it in GitHub Desktop.
Round time to next quarter hour with ruby (00,15,30,45)
This file contains hidden or 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
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 |
This file contains hidden or 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
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