Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Programming example
class IncorrectTimeFormatError < StandardError; end
class FakeTime
##
# :call-seq:
# FakeTime.add_minutes(time, minutes_to_add) => String
#
# Returns a new string with minutes_to_add added to the time
#
# FakeTime.add_minutes("9:23 AM", 10) #=> "9:33 AM"
#
#
def self.add_minutes(time, minutes_to_add)
if matches = time.match(/\A(1[0-2]|\d):(\d{2}) (AM|PM)\z/i)
#split the time string
all, hours, minutes, ampm = matches.to_a
#sanitize hours/ampm
ampm.upcase!
hours = hours.to_i
#convert to 24 hour format
if ampm.match(/PM/)
hours += 12
end
#add minutes to running total
total_minutes = minutes.to_i + minutes_to_add.to_i
minutes = total_minutes % 60
#calculate new total for hours
hours = hours + total_minutes / 60
#convert back to 12 hour format
if hours % 24 / 12 == 1
ampm = "PM"
else
ampm = "AM"
end
hours = hours % 12
hours = hours == 0 ? 12 : hours
"#{hours}:#{"%02d" % minutes} #{ampm}"
else
raise IncorrectTimeFormatError.new("#{time} is not in the format [H]H:MM [AM|PM]")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment