An object that represents a date or time.
For example, you can get the current time with the now method.
irb(main):020:0> Time.now
=> 2020-11-13 23:26:39.001668 +0900
You can create a Time object that represents any date and time with the new method.
irb(main):021:0> datetime = Time.new(2020, 1, 1, 12, 30
)
=> 2020-01-01 12:30:00 +0900
You can display the date and time in the specified format by using the strftime method. For example, to display in a format such as ** 2020-01-01 12:30 **, write as follows.
irb(main):021:0> datetime = Time.new(2020, 1, 1, 12, 30
)
=> 2020-01-01 12:30:00 +0900
irb(main):022:0> datetime.strftime('%Y-%m-%d %H:%M')
=> "2020-01-01 12:30"
irb(main):023:0>
Unlike the Time object, use this when you do not need to handle the time.
Note that you should load the date library in advance before using it.
irb(main):023:0> require 'date'
=> true
irb(main):024:0> Date
=> Date
Use the today method.
irb(main):025:0> Date.today
=> #<Date: 2020-11-13 ((2459167j,0s,0n),+0s,2299161j)>
Use new as well as Time.
irb(main):029:0> Date.new(2020, 1, 1)
=> #<Date: 2020-01-01 ((2458850j,0s,0n),+0s,2299161j)>
Like the Time object, you can specify the format to represent the date. Here, it is displayed in ** 2020/01/01 ** format from the Date object.
irb(main):030:0> Date.new(2020, 1, 1).strftime('%Y/%m/%
d')
=> "2020/01/01"
Recommended Posts