Skip to content

Instantly share code, notes, and snippets.

@doches
Created September 5, 2012 22:50
Show Gist options
  • Save doches/3646816 to your computer and use it in GitHub Desktop.
Save doches/3646816 to your computer and use it in GitHub Desktop.
Compute the difference in minutes between two RFC2822-formatted dates
#!/usr/bin/env ruby
# A Ruby function to compute the difference in minutes between two
# RFC2822-formatted dates. Tested on Ruby 1.8.7
#
# Note: this feels a bit cheeky, since Ruby's standard library has excellent
# support for timestamp conversions; this is basically a CLI wrapper around
# Time#rfc2822 and the subtraction operator between Time objects. Then again,
# this is the *reason* I'd use Ruby for a task like this (over, say, C++)...
#
# Author::Trevor Fountain (trevor@texasexpat.net)
def minutes_between(date1, date2)
begin
times = [date1, date2].map { |s| Time.rfc2822(s) }
rescue ArgumentError
# If our arguments aren't valid RFC2822-formatted timestamps, (re-)raise
# an error
#
# If we wanted to silently ignore malformed dates and do something
# sensible, we might return a zero or negative difference here instead.
raise $1
rescue TypeError
# If our arguments aren't strings or something from which we can extract
# an RFC2822-formatted date, raise an error
raise ArgumentError.new("expected two RFC2822-formatted strings, received #{date1.class} and #{date2.class}")
end
return ((times[0] - times[1])/60).abs.floor
end
# If we're running as a script:
# + read two strings from the command line
# + treat them as RFC2822-formatted dates
# + print the difference in minutes to STDOUT
if __FILE__ == $0
# Die with usage info if invoked with wrong number of arguments
if ARGV.size != 2
STDERR.puts "Compute the difference in minutes between two RFC2822-formatted dates"
STDERR.puts ""
STDERR.puts "Usage: #{$0} \"date\" \"date\""
exit(1)
end
date1, date2 = *ARGV
puts minutes_between(date1, date2)
end
@doches
Copy link
Author

doches commented Sep 6, 2012

As I mentioned in the notes, this feels like a bit of a cheeky answer to the coding prompt. If you agree, and would rather see an implementation that doesn't rely on lots of useful standard library stuff (i.e. an implementation that would never see the light of day in a real project!) I'll gladly put one together just to, you know, prove that I could. Which I suppose is the point of the exercise...

Otherwise, this is how I'd solve the problem. The library calls I'm using are significantly more tested than anything I might put together, and written by programmers who are likely to be rather more clever than I.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment