August 11th, 2007
Parsing Dates in Unix with Ruby
Ever need to write a script that can read a human readable date and turn it into something a computer can use? How often do you have “August 10, 2007” in a string and need that converted to a number of seconds since January 1, 1970?
As it turns out, Ruby includes an excellent module for parsing dates. It can handle several common formats, too! All you need to do is require ‘parsedate’ and you have access to it:
(Text in bold is what you would type.)
require 'parsedate' user_input = ARGF.readline seconds = Time.local(*ParseDate.parsedate(user_input)).to_i puts seconds % ruby parsedate_example August 10, 2007 1186722000
If you are in a hurry, try a one-liner:
% ruby -rparsedate -nle \ 'print Time.local(*ParseDate.parsedate($_)).to_i' August 10, 2007 1186722000 2006-09-21 1158814800 2001 sep 8 999925200
If you deal with /etc/shadow
a lot you will find this useful for figuring out what today is in terms of the password last changed field by dividing the given number by 86400 (the number of seconds in each day):
% ruby -rparsedate -nle \ 'print Time.local(*ParseDate.parsedate($_)).to_i / 86400' August 10, 2007 13735
Or do it in reverse with Time.at:
% env TZ=GMT ruby -nle 'print Time.at($_.to_i * 86400)' 13735 Fri Aug 10 00:00:00 +0000 2007
With Ruby you never need to venture far to manage your dates! Let me know if you find this useful or if you have questions about similar should-be-easy problems you encounter!