2

I have a long value in Rails, 134740800, which is the number of milliseconds since the epoch.

How do I convert that to a date in mm-dd-yyyy format?

I figure the formatting would be done with something like strftime but I can't seem to find the right method to convert the long into a valid date.

1
  • sry meant seconds, Time.at was what I was looking for, thank you all
    – HelloWorld
    Sep 13, 2012 at 17:20

5 Answers 5

6
secs = 134740800/1000 # millisecs / 1000
t = Time.at(secs)
t.strftime("%m-%d-%Y")

Output

"01-02-1970"
2

Try this:

require 'date'
DateTime.strptime("1318996912",'%s')
2

I assume you mean seconds since the epoch.

Time.at seconds_since_epoch

You can also pass a float. If you have milliseconds, divide by 1000.0 first. You can then call strftime on the returned Time object.

1

Use Time.at:

irb(main):003:0> Time.at(134740800)
=> Tue Apr 09 08:00:00 -0400 1974
0

This is an advisory... It's often a good idea to look at how fast some answers run. Here's a simple benchmark:

require 'benchmark'
require 'date'

SECS = 134740800
LOOPS = 1_000_000

puts Time.at(SECS).strftime('%m-%d-%Y')
puts Date.strptime(SECS.to_s, '%s').strftime('%m-%d-%Y')

Benchmark.bm(14) do |x|
  x.report('Time.at:') { LOOPS.times { Time.at(SECS) }}
  x.report('Date.strptime:') { LOOPS.times { Date.strptime(SECS.to_s, '%s') }}
end

And the output is:

04-09-1974
04-09-1974
                     user     system      total        real
Time.at:         0.370000   0.020000   0.390000 (  0.392761)
Date.strptime:   6.320000   0.050000   6.370000 (  6.373248)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.