Convert Ruby Date to Integer

How to convert Ruby date to integer?

+42
date ruby datetime ruby-on-rails
Dec 20 '10 at 18:17
source share
5 answers

You cannot convert a date in Ruby directly to an integer. If you try, you will get:

$ Date.today.to_i $ NoMethodError: undefined method 'to_i' for Wed, 06 Dec 2017:Date 

However, you can rotate the date into time, and then get the number from this:

 $ Date.today.to_time.to_i #=> 1512536400 
+3
Dec 06 '17 at 18:59
source share
 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 
+81
Dec 20 '10 at 18:22
source share

Time.now.to_i

seconds since the creation of the era

+8
Dec 20 '10 at 18:23
source share

The solution for Ruby 1.8 is 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" 
+7
Nov 03 '13 at 15:09
source share

A date cannot immediately become an integer. Example:

 $ 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: either include a date and then Int, which will give you seconds from an era:

 $ Date.today.to_time.to_i => 1514523600 

Or come up with some other number you want, like days from an era:

 $ Date.today.to_time.to_i / (60 * 60 * 24) ### Number of seconds in a day => 17529 ### Number of days since epoch 
+3
Dec 29 '17 at 20:25
source share



All Articles