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.

Community
  • 1
  • 1
ljnissen
  • 139
  • 1
  • 12

2 Answers2

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.

nishu
  • 1,493
  • 11
  • 26
1

You could use Time.parse...

database_entry = '2014-05-14'
Time.parse(database_entry)
=> => 2014-05-14 00:00:00 +0100
SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53