Ruby, Part 2 — Dates
I have a theory that we should judge a language by how it handles dates out of the box. I’m not saying that dates are trivial (because they aren’t) but sooner or later we are going to have to write some code that compares dates, figures dates, etc. Since we are all going to do it sometime, the language should make it easy to do out of the box.
With that litmus test, Java would not score well, since it makes you jump through hoops (Calendar, anyone? ). Perl would do even worse, since all it has is localtime. Python wasn’t much better until they introduced datetime. Though strptime is still in the time module and there isn’t a very direct way to change a time tuple to a datetime (though it’s possible).
Enough ranting about other languages — this is about Ruby and how it does dates and time (I just call them “dates”). Ruby has it’s own DateTime module as well as Date and Time. I played with Date a little but then moved to DateTime — this is probably what I would do more often. The strptime format works well — it uses the same format characters as C’s strptime, which is a good thing (and, really, the easiest for Ruby developers to write). You can add integers to a DateTime object, print them, etc. Very nice stuff.
Here is the script I wrote to play around with this:
#!/usr/bin/ruby
require 'date'
datestr=`date`
mydate = DateTime.strptime(datestr,"%a %b %d %H:%M:%S %Z %Y")
puts mydate
bday = DateTime.new(1974,9,18)
puts bday
## these aren't seconds, I don't think . .
diff=mydate-bday
puts "I am #{diff} secs old"
tomorrow = mydate + 1
puts tomorrow