On Saturday 27 August 2005 4:07 pm, Joel VanderWerf wrote:
> Is there a way to use Time#strftime to generate a string that contains
> milliseconds, and to do so in such a way that Time.parse understands it?
>
> In other words, a value of ms_format that makes this work:
>
> t_now = Time.at(1125180070.216)
> diff = Time.parse(t_now.strftime(ms_format)) - t_now
> diff.abs < 0.001 # ==> true

Time.parse works via ParseDate.parsedate, and that, in turn, passes all the 
heavy lifting to Date._parse.  Date._parse, nifty bit of code that it is, 
does parse out fractional seconds.  However, parsedate doesn't look for the 
fractional seconds, so they get lost in the conversion back to a Time object.

And if one reimplements the parsedate method to not ignore the fractional 
seconds, one runs into other problems with Time when it encounters that.  So, 
while I'd love to be wrong, the only way that I see around this is dealing 
with the fractional seconds yourself by reopening Time and overriding 
Time#parse.

Here's one way.  If you put this in an external file, require it after you 
require 'time'.

class Time
  class << Time
    alias :parse_old :parse
    def parse(date, now=Time.now)
      t = parse_old(date,now)
      d = Date._parse(date)
      t += d[:sec_fraction].to_f if d.has_key? :sec_fraction
    end
  end
end

And here's an example of it in use:

irb(main):003:0> a = Time.parse('23 Aug 2005 19:00:01.1')
=> Tue Aug 23 19:00:01 MDT 2005
irb(main):004:0> a.to_f
=> 1124845201.1
irb(main):005:0> b = Time.parse('23 Aug 2005 19:00:01.9')
=> Tue Aug 23 19:00:01 MDT 2005
irb(main):006:0> b.to_f
=> 1124845201.9
irb(main):007:0> b-a
=> 0.8


Kirk Haines