Here’s a demonstration of several Ruby methods for date/time conversion:
$ irb
irb(main):005:0> require 'date'
=> false
irb(main):006:0> dt = Date.new(2020,12,25)
irb(main):007:0> dt
=> #<Date: 2020-12-25 ((2459209j,0s,0n),+0s,2299161j)>
irb(main):008:0> dt.to_time
=> 2020-12-25 00:00:00 -0800
irb(main):009:0> dt.to_time.to_i
=> 1608883200
irb(main):010:0> tm = Time.at(1608883200)
=> 2020-12-25 00:00:00 -0800
irb(main):011:0> dtm = tm.to_datetime
=> "2020-12-25T00:00:00-08:00"
irb(main):017:0> dtm.strftime("%A, %B %e, %Y")
=> "Friday, December 25, 2020"
This does the following:
- Requires the
Date
standard library - Creates a date
- Converts a date to a
Time
object - Converts a
Time
instance to an integer value representing the number of seconds since the Unix epoch (January 1, 1970) - Calls the
Time
class methodat
to instantiate a newTime
object based on this number of seconds - Converts this time to a
DateTime
- Uses string formatting to return a custom presentation
The last method is particularly useful–see the strftime
documentation for a full listing of formatting options.