Method: ActiveSupport::TimeZone#iso8601
- Defined in:
- activesupport/lib/active_support/values/time_zone.rb
permalink #iso8601(str) ⇒ Object
Method for creating new ActiveSupport::TimeWithZone instance in time zone of self
from an ISO 8601 string.
Time.zone = 'Hawaii' # => "Hawaii"
Time.zone.iso8601('1999-12-31T14:00:00') # => Fri, 31 Dec 1999 14:00:00 HST -10:00
If the time components are missing then they will be set to zero.
Time.zone = 'Hawaii' # => "Hawaii"
Time.zone.iso8601('1999-12-31') # => Fri, 31 Dec 1999 00:00:00 HST -10:00
If the string is invalid then an ArgumentError
will be raised unlike parse
which usually returns nil
when given an invalid date string.
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 |
# File 'activesupport/lib/active_support/values/time_zone.rb', line 387 def iso8601(str) # Historically `Date._iso8601(nil)` returns `{}`, but in the `date` gem versions `3.2.1`, `3.1.2`, `3.0.2`, # and `2.0.1`, `Date._iso8601(nil)` raises `TypeError` https://github.com/ruby/date/issues/39 # Future `date` releases are expected to revert back to the original behavior. raise ArgumentError, "invalid date" if str.nil? parts = Date._iso8601(str) year = parts.fetch(:year) if parts.key?(:yday) ordinal_date = Date.ordinal(year, parts.fetch(:yday)) month = ordinal_date.month day = ordinal_date.day else month = parts.fetch(:mon) day = parts.fetch(:mday) end time = Time.new( year, month, day, parts.fetch(:hour, 0), parts.fetch(:min, 0), parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0), parts.fetch(:offset, 0) ) if parts[:offset] TimeWithZone.new(time.utc, self) else TimeWithZone.new(nil, self, time) end rescue Date::Error, KeyError raise ArgumentError, "invalid date" end |