Skip to content

Instantly share code, notes, and snippets.

@michaelminter
Created April 6, 2013 02:01
Show Gist options
  • Select an option

  • Save michaelminter/5324363 to your computer and use it in GitHub Desktop.

Select an option

Save michaelminter/5324363 to your computer and use it in GitHub Desktop.
Without using any date/time library, write a function or method that accepts two mandatory arguments. The first argument is a string of the format[H]H:MM {AM|PM} and the second argument is an integer. Assume the integer is the number of minutes to add to the string. The return value of the function should be a string of the same format as the fi…
#! /usr/bin/env ruby
# Without using any date/time library, write a function or method that accepts
# two mandatory arguments. The first argument is a string of the format[H]H:MM
# {AM|PM} and the second argument is an integer. Assume the integer is the
# number of minutes to add to the string. The return value of the function
# should be a string of the same format as the first argument. For example
# add_minutes('9:13 AM', 10) would return 9:23 AM.
# To run:
# $ ruby peoples_test.rb <string="9:45 PM"> <int=60>
def format_time(hours,minutes,period)
return "#{hours}:#{minutes} #{period}"
end
def add_minutes (time, append = 0)
# check time formatting
unless /^(?<hours>[0-9]{1,2}):(?<minutes>[0-9]{2})\s(?<period>(AM|PM))$/i =~ time
raise ArgumentError, 'First argument: time (string) is invalid. (Inproper date format)'
end
# check that hours is proper format
if hours.to_i > 12
raise ArgumentError, 'First argument: time (string) is invalid. (Inproper date format)'
end
# check minutes is integer
unless append.is_a? Integer
raise ArgumentError, 'Second argument: minutes (int) is invalid.'
end
# Evaluate input time
output = ""
hours = hours.to_i
minutes = minutes.to_i
period = period.upcase
long_hours = (hours % 12) + (period == 'AM' ? 0 : 12) # Convert 12 hour format to 24 hour format
return format_time(hours,minutes+append,period) if (minutes + append) <= 59
more_hours = (minutes + append) / 60 # retrieve leftover hours
more_minutes = (minutes + append) % 60 # retreive leftover minutes
mod_hours = (long_hours + more_hours) % 24 # combine leftover hours and maintain 24 hour format
period = (mod_hours > 11 ? "PM" : "AM") # convert period based on long hour
short_hours = ((mod_hours % 12) > 0 ? (mod_hours % 12) : 12) # convert to 12 hour format
return format_time(short_hours, more_minutes, period)
end
input_time = ARGV[0]
input_minutes = ARGV[1]
print "#{add_minutes input_time, input_minutes.to_i}\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment