ruby - Time.now does not match the same Time as generated from Time.parse or Time.at -


while testing ruby code, ran strange behavior. can please explain why time.now doesn't match same time created either time.at or parsed time.parse?

[1] pry(main)> require 'time' => true [2] pry(main)> t = time.now => 2013-04-04 19:46:49 -0400 [3] pry(main)> = time.at t.to_i => 2013-04-04 19:46:49 -0400 [4] pry(main)> t == => false [5] pry(main)> t.to_i == i.to_i => true [6] pry(main)> p = time.parse t.to_s => 2013-04-04 19:46:49 -0400 [7] pry(main)> t == p => false [8] pry(main)> t.to_i == p.to_i => true [8] pry(main)> t.class => time [9] pry(main)> i.class => time [10] pry(main)> p.class => time [11] pry(main)> t.inspect => "2013-04-04 19:46:49 -0400" [12] pry(main)> i.inspect => "2013-04-04 19:46:49 -0400" [13] pry(main)> p.inspect => "2013-04-04 19:46:49 -0400" 

update 1

it seems trying sub-second precision shows same behavior:

[1] pry(main)> t = time.now => 2013-04-04 20:04:47 -0400 [2] pry(main)> f = time.at t.to_f => 2013-04-04 20:04:47 -0400 [3] pry(main)> t == f => false [4] pry(main)> t.to_f => 1365120287.902954 [5] pry(main)> f.to_f => 1365120287.902954 

i'll take shot @ 'splaining you're seeing. here several comparisons of time value, , happens when converting between different formats. i'm not going equality checks, because you'll able see whether value should match looking @ it:

require 'time'                                          t_now = time.now # => 2013-04-04 20:10:17 -0700 

that's inspect output, throws away lot of information , precision. it's enough use mortals.

t_now.to_f # => 1365131417.613106 

that's value computer sees usually, microseconds.

t_now.to_i # => 1365131417 

that's same time microseconds gone.

time.at(t_now)      # => 2013-04-04 20:10:17 -0700 time.at(t_now.to_f) # => 2013-04-04 20:10:17 -0700 time.at(t_now.to_i) # => 2013-04-04 20:10:17 -0700 t_now.to_s          # => "2013-04-04 20:10:17 -0700" 

normal inspect , to_s output won't show difference in precision long integer portion of value intact.

time.parse(t_now.to_s)      # => 2013-04-04 20:10:17 -0700 time.parse(t_now.to_s).to_f # => 1365131417.0 

parsing loses resolution, unless present value contains fractional time , define parsing format strptime knows it. default parser formats designed general-use, not high-precision, have use strftime instead of allowing to_s have way value, , strptime know numbers mean:

t_format = '%y/%m/%d-%h:%m:%s.%n' # => "%y/%m/%d-%h:%m:%s.%n" t_now.strftime(t_format)          # => "2013/04/04-20:10:17.613106000" time.strptime(t_now.strftime(t_format), t_format).to_f # => 1365131417.613106 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -