How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

后端 未结 6 628
孤城傲影
孤城傲影 2020-11-30 16:21

How do you convert a Unix timestamp (seconds since epoch) to Ruby DateTime?

6条回答
  •  野性不改
    2020-11-30 17:01

    Sorry, brief moment of synapse failure. Here's the real answer.

    require 'date'
    
    Time.at(seconds_since_epoch_integer).to_datetime
    

    Brief example (this takes into account the current system timezone):

    $ date +%s
    1318996912
    
    $ irb
    
    ruby-1.9.2-p180 :001 > require 'date'
     => true 
    
    ruby-1.9.2-p180 :002 > Time.at(1318996912).to_datetime
     => # 
    

    Further update (for UTC):

    ruby-1.9.2-p180 :003 > Time.at(1318996912).utc.to_datetime
     => #
    

    Recent Update: I benchmarked the top solutions in this thread while working on a HA service a week or two ago, and was surprised to find that Time.at(..) outperforms DateTime.strptime(..) (update: added more benchmarks).

    # ~ % ruby -v
    #  => ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-darwin13.0]
    
    irb(main):038:0> Benchmark.measure do
    irb(main):039:1*   ["1318996912", "1318496912"].each do |s|
    irb(main):040:2*     DateTime.strptime(s, '%s')
    irb(main):041:2>   end
    irb(main):042:1> end
    
    => #
    
    irb(main):044:0> Benchmark.measure do
    irb(main):045:1>   [1318996912, 1318496912].each do |i|
    irb(main):046:2>     DateTime.strptime(i.to_s, '%s')
    irb(main):047:2>   end
    irb(main):048:1> end
    
    => #
    
    irb(main):050:0* Benchmark.measure do
    irb(main):051:1*   ["1318996912", "1318496912"].each do |s|
    irb(main):052:2*     Time.at(s.to_i).to_datetime
    irb(main):053:2>   end
    irb(main):054:1> end
    
    => #
    
    irb(main):056:0* Benchmark.measure do
    irb(main):057:1*   [1318996912, 1318496912].each do |i|
    irb(main):058:2*     Time.at(i).to_datetime
    irb(main):059:2>   end
    irb(main):060:1> end
    
    => #
    

提交回复
热议问题