Convert Ruby Date to Integer

Ruby on-RailsRubyDatetimeDate

Ruby on-Rails Problem Overview


How can I convert a Ruby Date to an integer?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

t = Time.now
# => 2010-12-20 11:20:31 -0700

# Seconds since epoch
t.to_i
#=> 1292869231

require 'date'
d = Date.today
#=> #<Date: 2010-12-20 (4911101/2,0,2299161)>

epoch = Date.new(1970,1,1)
#=> #<Date: 1970-01-01 (4881175/2,0,2299161)>

d - epoch
#=> (14963/1)

# Days since epoch
(d - epoch).to_i
#=> 14963

# Seconds since epoch
d.to_time.to_i
#=> 1292828400

Solution 2 - Ruby on-Rails

Date cannot directly become an integer. Ex:

$ Date.today
=> #<Date: 2017-12-29 ((2458117j,0s,0n),+0s,2299161j)>
$ Date.today.to_i
=> NoMethodError: undefined method 'to_i' for #<Date: 2017-12-29 ((2458117j,0s,0n),+0s,2299161j)>

Your options are either to turn the Date into a time then an Int which will give you the seconds since epoch:

$ Date.today.to_time.to_i
=> 1514523600

Or come up with some other number you want like days since epoch:

$ Date.today.to_time.to_i / (60 * 60 * 24)  ### Number of seconds in a day
=> 17529   ### Number of days since epoch

Solution 3 - Ruby on-Rails

Time.now.to_i

returns seconds since epoch format

Solution 4 - Ruby on-Rails

Solution for Ruby 1.8 when you have an arbitrary DateTime object:

1.8.7-p374 :001 > require 'date'
 => true 
1.8.7-p374 :002 > DateTime.new(2012, 1, 15).strftime('%s')
 => "1326585600"

Solution 5 - Ruby on-Rails

I had to do it recently and took some time to figure it out but that is how I came across a solution and it may give you some ideas:

require 'date'
today = Date.today

year = today.year
month = today.mon
day = day.mday

year = year.to_s

month = month.to_s

day = day.to_s    


if month.length <2
  month = "0" + month
end

if day.length <2
  day = "0" + day
end

today = year + month + day

today = today.to_i

puts today

At the date of this post, It will put 20191205.

In case the month or day is less than 2 digits it will add a 0 on the left.

I did like this because I had to compare the current date whit some data that came from a DB in this format and as an integer. I hope it helps you.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrigView Question on Stackoverflow
Solution 1 - Ruby on-RailsPhrogzView Answer on Stackoverflow
Solution 2 - Ruby on-Railsuser9153631View Answer on Stackoverflow
Solution 3 - Ruby on-RailsEnabrenTaneView Answer on Stackoverflow
Solution 4 - Ruby on-RailsNowakerView Answer on Stackoverflow
Solution 5 - Ruby on-RailsWagner BragaView Answer on Stackoverflow