跳至內文 跳至搜尋

Active Model Time 類型

時分秒顯示的屬性類型。此類型是以 :time 鍵值註冊。

class Event
  include ActiveModel::Attributes

  attribute :start, :time
end

String 值會使用 ISO 8601 datetime 格式進行分析,但會統一採用 2000-01-01 的日期,以及 UTC 時區。

event = Event.new
event.start = "2004-10-25T01:23:45-06:00"

event.start.class # => Time
event.start       # => 2000-01-01 07:23:45 UTC

時間格式的部分內容也可以被接受。

event.start = "00:01:02+03:00"
event.start # => 1999-12-31 21:01:02 UTC

可以在宣告屬性時自訂次秒精度。

class Event
  include ActiveModel::Attributes

  attribute :start, :time, precision: 4
end
方法
T
U
包含的模組

實例公用方法

type()

# File activemodel/lib/active_model/type/time.rb, line 45
def type
  :time
end

user_input_in_time_zone(value)

# File activemodel/lib/active_model/type/time.rb, line 49
def user_input_in_time_zone(value)
  return unless value.present?

  case value
  when ::String
    value = "2000-01-01 #{value}"
    time_hash = begin
      ::Date._parse(value)
    rescue ArgumentError
    end

    return if time_hash.nil? || time_hash[:hour].nil?
  when ::Time
    value = value.change(year: 2000, day: 1, month: 1)
  end

  super(value)
end