Date class and Time class are used for date and time operations in Ruby. The Date class deals only with the date, and the Time class deals with the year, month, day, hour, minute, and second. I feel that I should use only the Time class, but since the Date class also has a strong field, I will explain how to use it properly.
First, use Time if you want to display up to hours, minutes, and seconds, that is, if you want to handle the date and time. You can also use the DateTime class, which is a subclass of the Date class, but considering that you have to require'date', daylight saving time, leap seconds, etc., it seems safe to use the Time class. ..
It is convenient to use the Date class for processing by date or year.
[1]pry(main)> Date.today.next_month #Same day next month
=> #<Date: 2020-10-29 ((2459152j,0s,0n),+0s,2299161j)>
[2] pry(main)> Date.new(2020,10,-1) #Last day (October 2020)
=> #<Date: 2020-10-31 ((2459154j,0s,0n),+0s,2299161j)>
[3] pry(main)> Date.today.leap? #Judgment of leap year (this year = 2020)
=> true
[4] pry(main)> Date.today.next_year.leap? #Judgment of leap year (next year = 2021)
=> false
[5] pry(main)> Date.today + 3 #3 days later
=> #<Date: 2020-10-02 ((2459125j,0s,0n),+0s,2299161j)>
[6] pry(main)> Date.today - 7 #1 week ago (7 days ago)
=> #<Date: 2020-09-22 ((2459115j,0s,0n),+0s,2299161j)>
[7] pry(main)> Date.today >> 6 #Half a year later (6 months later)
=> #<Date: 2021-03-29 ((2459303j,0s,0n),+0s,2299161j)>
[8] pry(main)> Date.today << 1 #1 month ago
=> #<Date: 2020-08-29 ((2459091j,0s,0n),+0s,2299161j)>
It is convenient to be able to easily obtain the same day or the end of the next month, and determine the leap year. Also, date increment and decrement operations are a bit cumbersome in the Time class because they have to be handled in seconds. In that respect, in the Date class, daily units can be easily set to + and-, and monthly units can be set to << and >>.
Basically, you can use the Time class when you want to display up to the time, but it is convenient to use the Date class when you mainly process by day, month, or year.
Recommended Posts