From: Sam Roberts Date: 2004-04-01T03:08:00+09:00 Subject: Re: How to get internal state of DateTime in seconds Quoteing smejmoon@yahoo.com, on Thu, Apr 01, 2004 at 01:44:21AM +0900: > How do you get internal state in seconds of DateTime instance? > Or convert it to Time instance? There is no method to do this, I proposed it in my email: 'possible Time & DateTime RCR: reconciling and extending their apis' please reply to it if you'd like to see such a method added in the future! > I want to compare two times with variable precision. > Below is my try to parse time from Common Log Format. > > require 'date' > str1 = '20/Nov/2003:08:08:09 +0200' > str2 = '20/Nov/2003:08:04:09 +0200' > t1 = DateTime.strptime(str=str1, fmt='%d/%b/%Y:%H:%M:%S %Z') > t2 = DateTime.strptime(str=str2, fmt='%d/%b/%Y:%H:%M:%S %Z') > > #what is difference in minutes between these 2 times? It's not clear from the docs, but you can do this: [ensemble] ~/p/ruby/vcard $ irb18 -r date irb(main):001:0> t0 = DateTime.now irb(main):002:0> t0.to_s => "2004-03-31T12:57:41-0500" irb(main):003:0> t1 = DateTime.now irb(main):004:0> t1.to_s => "2004-03-31T12:57:50-0500" irb(main):005:0> r = t1-t0 => Rational(192691, 1920000000) irb(main):007:0> r.to_f * 24 * 60 * 60 => 8.671095 The difference between two DateTime objects is a Rational, a fraction of days. Multiply that by the number of seconds/day, and you get the number of seconds difference. You could implement Date#to_time() by taking the difference between self, and Date.civil(1970,1,1), which should give you difference in days, then multiply by seconds per day, then use Time.at(). Cheers, Sam