--Class that handles date and time in UNIX time
irb(main):001:0> Time.now
=> 2021-01-02 01:41:25.0792755 +0000
--Class that handles dates
irb(main):004:0> Date.today
=> Sat, 02 Jan 2021
--Classes that handle dates and times --Since it is a subclass of Date, you can use Date methods.
irb(main):003:0> DateTime.now
=> Sat, 02 Jan 2021 01:41:40 +0000
validation --The usual method (the same method as integer type and string type) does not work. --You need to define your own method to add the error statement and set it as validation.
validate :day_after_today
def day_after_today
errors.add(:food_date, 'Please enter a date in the past, including today') if !food_date.nil? && (food_date > Time.zone.today)
end
--Example of validation that will result in an error if you enter a date after tomorrow --valid, no s needed
If you do not set the time_zone, it will be recorded in Coordinated Universal Time (UTC) by default.
module App
class Application < Rails::Application
config.time_zone = 'Tokyo'
end
end
--Comparison between Time type and DateTime type is in seconds --The following is an example when validation is applied so that the difference between DateTime type variables is 12 hours or more.
def time_before_give
errors.add(:limit_time, 'Please enter the date and time 12 hours or more before the hem division time') if !limit_time.nil? && give_time - limit_time < 12 * 60 * 60
end
--Since it is not possible to change from Time type to DateTime type, it is necessary to follow the procedure of "Delete column ⇨ Add column".
Recommended Posts