Archive for April 2013

How to convert Time from/to epoch time in ruby

Monday, April 15, 2013 · Posted in , , ,

In ruby, we can find time from/to epoch time as below:

To Epoch Time:

To find current epoch time in seconds (10 digit) use below code,
    current_epoch_time =( Time.now.to_i)
                          or
    current_epoch_time =( Time.now.to_f).ceil

To find current epoch time in mili-seconds (13 digit) use below code,
    current_epoch_time =( Time.now.to_f*1000).ceil

From Epoch Time:

If we want Time from epoch time then use below code,

begin
   Time.at(current_epoch_time)
rescue RangeError => e
   Time.at(
current_epoch_time / 1000)
end


In above code,
1. current_epochtime is in integer.
2. If epochtime is in miliseconds (13 digit) then it will raise RangeError.
3. We have catch RangeError and find datetime accordingly.


I hope it's useful to work with epoch time in ruby.


Powered by Blogger.