Epoch Converter and Date/Time in Ruby

Quick Navigation

Date Object

The Date object handles date, hour, minute, second and offset. Let's create a Date object and print it out. The Date object also has various methods.



    require 'date'

    puts "Getting date using new method: "
    puts Date.new(2019,2,18)
    puts "Getting date using parse method: "
    puts Date.parse('2019-02-18')
    puts "Getting date using strptime method: "
    puts Date.strptime('18-02-2019', '%d-%m-%Y')

    puts "\n"
    d2 = Date.today()
    puts "d2: #{d2}"
    puts "d2.year: #{d2.year}"
    puts "d2.month: #{d2.month}"
    puts "d2.strftime: #{d2.strftime('%a %d %b %Y')}"

                

Output:



    Getting date using new method: 
    2019-02-18
    Getting date using parse method:
    2019-02-18
    Getting date using strptime method:
    2019-02-18

    d2: 2019-02-19
    d2.year: 2019
    d2.month: 2
    d2.strftime: Tue 19 Feb 2019

                


Time Object

The Time in Ruby helps you represent a specific point in time. The Time has three components: hour, minute, and second. These are stored by the Time object as the Unix Time or Epoch time.



    puts Time.now

    puts Time.new(2018, 1, 1)

    puts Time.at(1549429771)

    t = Time.now
    puts "Day: #{t.day}"
    puts "Month: #{t.month}"
    puts "Hour: #{t.hour}"

                

Output:



    2019-02-16 03:26:36 +0000
    2018-01-01 00:00:00 +0000
    2019-02-06 05:09:31 +0000
    Day: 16
    Month: 2
    Hour: 3

                


Convert from Epoch to Human Readable Date

There are different ways to do convert epoch or unix time to human readble date.



    require 'time'

    #1st way
    puts Time.at(1549429771)

    #2nd way
    puts DateTime.strptime("1318996912",'%s')

    #3rd way
    puts Time.at(1549430831).to_datetime

                

Output:



    2019-02-06 05:09:31 +0000
    2011-10-19T04:01:52+00:00
    2019-02-06T05:27:11+00:00

                


Convert from Human Readable Date to Epoch

There are also different ways to convert human readable date to epoch.



    require 'time'

    #1st way
    str = "2015-05-27T07:39:59Z"
    puts Time.parse(str).to_i

    #2nd way
    puts Time.new(2018, 1, 1).to_i

    #3rd way
    time = Time.new(2018, 1, 1)
    puts time.strftime("Unix time is %s")

                

Output:



    1432712399
    1514764800
    Unix time is 1514764800

                


Programming Languages: