Convert Ruby Date to Integer

Convert Ruby Date to Integer

Asked on December 27, 2018 in Ruby on Rails.
Add Comment


  • 3 Answer(s)

    Use this code. Because we cannot convert the date into integer directly.

    $ 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)>
    

    Turn the Date into a time then an Integer that returns seconds since epoch:

    $ Date.today.to_time.to_i
    => 1514523600
    

    Here is the code of number of seconds in a day since epoch.

    $ Date.today.to_time.to_i / (60 * 60 * 24) ### Number of seconds in a day
    => 17529 ### Number of days since epoch
    
    Answered on December 27, 2018.
    Add Comment

    By using this code , we can convert Ruby date to integer.

    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
    
    Answered on December 27, 2018.
    Add Comment

    When we have an arbitrary DateTime object we can achieve this thing very easily in php 1.8

    1.8.7-p374 :001 > require 'date'
    => true
    1.8.7-p374 :002 > DateTime.new(2012, 1, 15).strftime('%s')
    => "1326585600"
    
    Answered on December 27, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.