[RAILS] [Caution summary] Set Ruby time (Time type/Date type/DateTime type) in the column

Time type / Date type / DateTime type

Time type

--Class that handles date and time in UNIX time

irb(main):001:0> Time.now
=> 2021-01-02 01:41:25.0792755 +0000

Date type

--Class that handles dates

irb(main):004:0> Date.today
=> Sat, 02 Jan 2021

DateTime type

--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

Tokyo time setting

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

--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

Column type change

--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

[Caution summary] Set Ruby time (Time type/Date type/DateTime type) in the column
How to set the display time to Japan time in Rails
Variable type in ruby
How to set chrony when the time shifts in CentOS7
Set the time zone in the JVM of your Azure application
Is there no type in Ruby?