user3206440 user3206440 - 2 months ago 14
Ruby Question

Ruby - epoch time with milliseconds to local time string

I have the following UNIX epoch timestamp -

1475001600029


I need to convert it into
local
date-time of format -
2016/09/28 00:01:13.536


Things I've tried

irb(main):005:0> Time.at(1475001600079)
=> 48710-12-11 00:11:19 +0530 # gives a weird value for year


irb(main):010:0> Time.strptime(1475001600079.to_s, '%Q')
NoMethodError: undefined method `strptime' for Time:Class
from (irb):10
from C:/RailsInstaller/Ruby2.2.0/bin/irb:11:in `<main>'


How to go about this ?

RUby version is -
ruby 2.2.4p230 (2015-12-16 revision 53155) [i386-mingw32]

Answer

Try Time.at(1475001600079 / 1000.0).

The epoch time in ruby is in seconds, not milliseconds.

As to the NoMethodError, you need to require 'time' before you call Time::strptime.

Finally the format you need:

Time.at(1475001600079 / 1000.0).strftime('%Y/%m/%d %H:%M:%S.%3N')