2

I'm building a Rails App where I want to convert some database entries to timestamps. Trouble is that they are in the format yyyy-mm-dd which gives this wrong timestamp:

irb(main):005:0> Date.new(2014-05-14).to_time.to_i * 1000
=> 788914800000

Instead I want something like this:

irb(main):006:0> Date.new(2014,05,14).to_time.to_i * 1000
=> 1400018400000

So how do I go about doing that in Ruby?

I've looked at this thread, but although helpful, it doesn't really solve my problem.

2 Answers 2

3

You should use Date.parse instead of Date.new

Date.parse('2014-05-14').to_time.to_i * 1000

When Date.new is called with 2014-05-14 it mean that it is being passed 1995 as an year, hence the wrong timestamp.

0
1

You could use Time.parse...

database_entry = '2014-05-14'
Time.parse(database_entry)
=> => 2014-05-14 00:00:00 +0100
1
  • That is a neat solution. Thank you!
    – ljnissen
    Commented Aug 3, 2014 at 17:19

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.