Class: TZInfo::Timezone Abstract
Relationships & Source Files | |
Extension / Inclusion / Inheritance Descendants | |
Subclasses:
|
|
Super Chains via Extension / Inclusion / Inheritance | |
Instance Chain:
self,
Comparable
|
|
Inherits: | Object |
Defined in: | lib/tzinfo/timezone.rb |
Overview
The .get method returns an instance of either DataTimezone
or
LinkedTimezone
. The .get_proxy method and other methods returning
collections of time zones return instances of TimezoneProxy
.
The Timezone
class represents a time zone. It provides a factory method,
.get, to retrieve Timezone
instances by their identifier.
The #to_local method can be used to convert Time
and DateTime
instances to the local time for the zone. For example:
tz = TZInfo::Timezone.get('America/New_York')
local_time = tz.to_local(Time.utc(2005,8,29,15,35,0))
local_datetime = tz.to_local(DateTime.new(2005,8,29,15,35,0))
Local Time
and DateTime
instances returned by Timezone
have the
correct local offset.
The #local_to_utc method can by used to convert local Time
and
DateTime
instances to UTC. #local_to_utc ignores the UTC offset
of the supplied value and treats if it is a local time for the zone. For
example:
tz = TZInfo::Timezone.get('America/New_York')
utc_time = tz.local_to_utc(Time.new(2005,8,29,11,35,0))
utc_datetime = tz.local_to_utc(DateTime.new(2005,8,29,11,35,0))
Each time zone is treated as sequence of periods of time (TimezonePeriod
)
that observe the same offset (TimezoneOffset
). Transitions
(TimezoneTransition
) denote the end of one period and the start of the
next. The Timezone
class has methods that allow the periods, offsets and
transitions of a time zone to be interrogated.
All methods that take Time
objects as parameters can be used with
arbitrary Time
-like objects that respond to both to_i
and subsec
and
optionally #utc_offset.
The Timezone
class is thread-safe. It is safe to use class and instance
methods of Timezone
in concurrently executing threads. Instances of
Timezone
can be shared across thread boundaries.
The IANA Time Zone Database maintainers recommend that time zone identifiers
are not made visible to end-users (see Names of
timezones). The
Country
class can be used to obtain lists of time zones by country,
including user-friendly descriptions and approximate locations.
Class Attribute Summary
-
.default_dst ⇒ Boolean
rw
Returns the default value of the optional
dst
parameter of the #local_time, #local_datetime and #local_timestamp, #local_to_utc and #period_for_local methods (nil
,true
orfalse
). -
.default_dst=(value)
rw
Sets the default value of the optional
dst
parameter of the #local_datetime, #local_time, #local_timestamp, #local_to_utc and #period_for_local methods.
Class Method Summary
-
._load(data) ⇒ Timezone
Loads a
Timezone
from the serialized representation returned by #_dump. -
.all ⇒ Array<Timezone>
Returns an
Array
of all the available time zones. -
.all_country_zone_identifiers ⇒ Array<String>
Returns an
Array
of the identifiers of all the time zones that are observed by at least oneCountry
. -
.all_country_zones ⇒ Array<Timezone>
Returns an
Array
of all the time zones that are observed by at least oneCountry
. -
.all_data_zone_identifiers ⇒ Array<String>
time zones that are defined by offsets and transitions.
-
.all_data_zones ⇒ Array<Timezone>
Returns an
Array
of all the available time zones that are defined by offsets and transitions. - .all_identifiers ⇒ Array<String>
-
.all_linked_zone_identifiers ⇒ Array<String>
time zones that are defined as links to / aliases for other time zones.
-
.all_linked_zones ⇒ Array<Timezone>
Returns an
Array
of all the available time zones that are defined as links to / aliases for other time zones. -
.get(identifier) ⇒ Timezone
Returns a time zone by its IANA Time Zone Database identifier (e.g.
"Europe/London"
or"America/Chicago"
). -
.get_proxy(identifier) ⇒ TimezoneProxy
Returns a proxy for the time zone with the given identifier.
- .data_source ⇒ DataSource private
- .get_proxies(identifiers) ⇒ Array<TimezoneProxy> private
Instance Method Summary
-
#<=>(tz) ⇒ Integer
Compares this
Timezone
with another based on the #identifier. -
#=~(regexp) ⇒ Integer
Matches
regexp
against the #identifier of thisTimezone
. -
#_dump(limit) ⇒ String
Returns a serialized representation of this
Timezone
. -
#abbr(time = Time.now)
Alias for #abbreviation.
- #abbreviation(time = Time.now) ⇒ String (also: #abbr)
-
#base_utc_offset(time = Time.now) ⇒ Integer
Returns the base offset from UTC in seconds at the given time.
-
#canonical_identifier ⇒ String
Returns the canonical identifier of this time zone.
-
#canonical_zone ⇒ Timezone
Returns the canonical
Timezone
instance for thisTimezone
. - #current_period ⇒ TimezonePeriod
-
#current_period_and_time
Alias for #current_time_and_period.
-
#current_time_and_period ⇒ Array
(also: #current_period_and_time)
Returns the current local time and
TimezonePeriod
for the time zone as anArray
. - #dst?(time = Time.now) ⇒ Boolean
- #eql?(tz) ⇒ Boolean
-
#friendly_identifier(skip_first_part = false) ⇒ String
Returns #identifier, modified to make it more readable.
- #hash ⇒ Integer
- #identifier ⇒ String
- #inspect ⇒ String
-
#local_datetime(year, month = 1, day = 1, hour = 0, minute = 0, second = 0, sub_second = 0, dst = Timezone.default_dst) {|periods| ... } ⇒ DateTimeWithOffset
Creates a
DateTime
object based on the given (Gregorian calendar) date and time parameters. -
#local_time(year, month = 1, day = 1, hour = 0, minute = 0, second = 0, sub_second = 0, dst = Timezone.default_dst) {|periods| ... } ⇒ TimeWithOffset
Creates a
Time
object based on the given (Gregorian calendar) date and time parameters. -
#local_timestamp(year, month = 1, day = 1, hour = 0, minute = 0, second = 0, sub_second = 0, dst = Timezone.default_dst) {|periods| ... } ⇒ TimestampWithOffset
Creates a
Timestamp
object based on the given (Gregorian calendar) date and time parameters. -
#local_to_utc(local_time, dst = Timezone.default_dst) {|periods| ... } ⇒ Object
Converts a local time for the time zone to UTC.
- #name ⇒ String
- #now ⇒ TimeWithOffset
-
#observed_utc_offset(time = Time.now) ⇒ Integer
(also: #utc_offset)
Returns the observed offset from UTC in seconds at the given time.
-
#offsets_up_to(to, from = nil) ⇒ Array<TimezoneOffsets>
Returns the unique offsets used by the time zone up to a given time (
to
) as anArray
ofTimezoneOffset
instances. -
#period_for(time) ⇒ TimezonePeriod
Returns the
TimezonePeriod
that is valid at a given time. -
#period_for_local(local_time, dst = Timezone.default_dst) {|periods| ... } ⇒ TimezonePeriod
Returns the
TimezonePeriod
that is valid at the given local time. -
#period_for_utc(utc_time) ⇒ TimezonePeriod
Returns the
TimezonePeriod
that is valid at a given time. -
#periods_for_local(local_time) ⇒ Array<TimezonePeriod>
Returns the set of
TimezonePeriod
s that are valid for the given local time as anArray
. -
#strftime(format, time = Time.now) ⇒ String
Converts a time to local time for the time zone and returns a
String
representation of the local time according to the given format. -
#to_local(time) ⇒ Object
Converts a time to the local time for the time zone.
- #to_s ⇒ String
-
#transitions_up_to(to, from = nil) ⇒ Array<TimezoneTransition>
Returns an
Array
ofTimezoneTransition
instances representing the times where the UTC offset of the timezone changes. -
#utc_offset(time = Time.now)
Alias for #observed_utc_offset.
-
#utc_to_local(utc_time) ⇒ Object
Converts a time in UTC to the local time for the time zone.
-
#raise_unknown_timezone
private
Raises an
UnknownTimezone
exception.
Class Attribute Details
.default_dst ⇒ Boolean
(rw)
Returns the default value of the optional dst
parameter of the
#local_time, #local_datetime and #local_timestamp, #local_to_utc
and #period_for_local methods (nil
, true
or false
).
default_dst
defaults to nil
unless changed with .default_dst=.
# File 'lib/tzinfo/timezone.rb', line 110
def default_dst @@default_dst end
.default_dst=(value) (rw)
Sets the default value of the optional dst
parameter of the
#local_datetime, #local_time, #local_timestamp, #local_to_utc and
#period_for_local methods. Can be set to nil
, true
or false
.
# File 'lib/tzinfo/timezone.rb', line 96
def default_dst=(value) @@default_dst = value.nil? ? nil : !!value end
Class Method Details
._load(data) ⇒ Timezone
Loads a Timezone
from the serialized representation returned by #_dump.
This is method is called when using Marshal.load
or Marshal.restore
to restore a serialized Timezone
.
# File 'lib/tzinfo/timezone.rb', line 1147
def self._load(data) Timezone.get(data) end
.all ⇒ Array
<Timezone
>
Returns an Array
of all the available time zones.
TimezoneProxy
instances are returned to avoid the overhead of loading
time zone data until it is first needed.
# File 'lib/tzinfo/timezone.rb', line 151
def all get_proxies(all_identifiers) end
.all_country_zone_identifiers ⇒ Array
<String
>
Returns an Array
of the identifiers of all the time zones that are
observed by at least one Country
. This is not the complete set of time
zone identifiers as some are not country specific (e.g. 'Etc/GMT'
).
TimezoneProxy
instances are returned to avoid the overhead of loading
time zone data until it is first needed.
zones that are observed by at least one Country
.
.all_country_zones ⇒ Array
<Timezone
>
Returns an Array
of all the time zones that are observed by at least
one Country
. This is not the complete set of time zones as some are
not country specific (e.g. 'Etc/GMT'
).
TimezoneProxy
instances are returned to avoid the overhead of loading
time zone data until it is first needed.
.all_data_zone_identifiers ⇒ Array
<String
>
time zones that are defined by offsets and transitions.
# File 'lib/tzinfo/timezone.rb', line 175
def all_data_zone_identifiers data_source.data_timezone_identifiers end
.all_data_zones ⇒ Array
<Timezone
>
Returns an Array
of all the available time zones that are
defined by offsets and transitions.
TimezoneProxy
instances are returned to avoid the overhead of loading
time zone data until it is first needed.
# File 'lib/tzinfo/timezone.rb', line 169
def all_data_zones get_proxies(all_data_zone_identifiers) end
.all_identifiers ⇒ Array
<String
>
# File 'lib/tzinfo/timezone.rb', line 157
def all_identifiers data_source.timezone_identifiers end
.all_linked_zone_identifiers ⇒ Array
<String
>
time zones that are defined as links to / aliases for other time zones.
# File 'lib/tzinfo/timezone.rb', line 193
def all_linked_zone_identifiers data_source.linked_timezone_identifiers end
.all_linked_zones ⇒ Array
<Timezone
>
Returns an Array
of all the available time zones that are
defined as links to / aliases for other time zones.
TimezoneProxy
instances are returned to avoid the overhead of loading
time zone data until it is first needed.
# File 'lib/tzinfo/timezone.rb', line 187
def all_linked_zones get_proxies(all_linked_zone_identifiers) end
.data_source ⇒ DataSource (private)
# File 'lib/tzinfo/timezone.rb', line 234
def data_source DataSource.get end
.get(identifier) ⇒ Timezone
Returns a time zone by its IANA Time Zone Database identifier (e.g.
"Europe/London"
or "America/Chicago"
). Call .all_identifiers for a
list of all the valid identifiers.
The get
method will return a subclass of Timezone
, either a
DataTimezone
(for a time zone defined by rules that set out when
transitions occur) or a LinkedTimezone
(for a time zone that is just a
link to or alias for a another time zone).
# File 'lib/tzinfo/timezone.rb', line 127
def get(identifier) data_source.get_timezone_info(identifier).create_timezone end
.get_proxies(identifiers) ⇒ Array
<TimezoneProxy> (private)
# File 'lib/tzinfo/timezone.rb', line 229
def get_proxies(identifiers) identifiers.collect {|identifier| get_proxy(identifier)} end
.get_proxy(identifier) ⇒ TimezoneProxy
Returns a proxy for the time zone with the given identifier. This allows loading of the time zone data to be deferred until it is first needed.
The identifier will not be validated. If an invalid identifier is specified, no exception will be raised until the proxy is used.
# File 'lib/tzinfo/timezone.rb', line 141
def get_proxy(identifier) TimezoneProxy.new(identifier) end
Instance Method Details
#<=>(tz) ⇒ Integer
Compares this Timezone
with another based on the #identifier.
# File 'lib/tzinfo/timezone.rb', line 1105
def <=>(tz) return nil unless tz.is_a?(Timezone) identifier <=> tz.identifier end
#=~(regexp) ⇒ Integer
Matches regexp
against the #identifier of this Timezone
.
# File 'lib/tzinfo/timezone.rb', line 1128
def =~(regexp) regexp =~ identifier end
#_dump(limit) ⇒ String
Returns a serialized representation of this Timezone
. This method is
called when using Marshal.dump
with an instance of Timezone
.
# File 'lib/tzinfo/timezone.rb', line 1137
def _dump(limit) identifier end
#abbr(time = Time.now)
Alias for #abbreviation.
# File 'lib/tzinfo/timezone.rb', line 1051
alias abbr abbreviation
#abbreviation(time = Time.now) ⇒ String
Also known as: #abbr
# File 'lib/tzinfo/timezone.rb', line 1048
def abbreviation(time = Time.now) period_for(time).abbreviation end
#base_utc_offset(time = Time.now) ⇒ Integer
Returns the base offset from UTC in seconds at the given time. This does not include any adjustment made for daylight savings time and will typically remain constant throughout the year.
To obtain the observed offset from UTC, including the effect of daylight savings time, use #observed_utc_offset instead.
If you require accurate base_utc_offset
values, you should install the
tzinfo-data gem and set DataSources::RubyDataSource
as the DataSource
.
When using DataSources::ZoneinfoDataSource
, the value of
base_utc_offset
has to be derived from changes to the observed UTC
offset and DST status since it is not included in zoneinfo files.
# File 'lib/tzinfo/timezone.rb', line 1081
def base_utc_offset(time = Time.now) period_for(time).base_utc_offset end
#canonical_identifier ⇒ String
Returns the canonical identifier of this time zone.
This is a shortcut for calling canonical_zone.identifier
. Please refer
to the #canonical_zone documentation for further information.
# File 'lib/tzinfo/timezone.rb', line 987
def canonical_identifier canonical_zone.identifier end
#canonical_zone ⇒ Timezone
Returns the canonical Timezone
instance for this Timezone
.
The IANA Time Zone database contains two types of definition: Zones and Links. Zones are defined by rules that set out when transitions occur. Links are just references to fully defined Zone, creating an alias for that Zone.
Links are commonly used where a time zone has been renamed in a release of the Time Zone database. For example, the US/Eastern Zone was renamed as America/New_York. A US/Eastern Link was added in its place, linking to (and creating an alias for) America/New_York.
Links are also used for time zones that are currently identical to a full Zone, but that are administered separately. For example, Europe/Vatican is a Link to (and alias for) Europe/Rome.
For a full Zone (implemented by DataTimezone
), canonical_zone
returns
self.
For a Link (implemented by LinkedTimezone
), canonical_zone
returns a
Timezone
instance representing the full Zone that the link targets.
::TZInfo
can be used with different data sources (see the documentation for
DataSource
). Some DataSource implementations may not support
distinguishing between full Zones and Links and will treat all time zones
as full Zones. In this case, canonical_zone
will always return self
.
There are two built-in DataSource
implementations.
DataSources::RubyDataSource
(which will be used if the tzinfo-data gem
is available) supports Link zones. DataSources::ZoneinfoDataSource
returns Link zones as if they were full Zones. If the canonical_zone
or
#canonical_identifier methods are needed, the tzinfo-data gem should be
installed.
The DataSource.get method can be used to check which DataSource
implementation is being used.
# File 'lib/tzinfo/timezone.rb', line 412
def canonical_zone raise_unknown_timezone end
#current_period ⇒ TimezonePeriod
# File 'lib/tzinfo/timezone.rb', line 997
def current_period period_for(Time.now) end
#current_period_and_time
Alias for #current_time_and_period.
# File 'lib/tzinfo/timezone.rb', line 1018
alias current_period_and_time current_time_and_period
#current_time_and_period ⇒ Array
Also known as: #current_period_and_time
Returns the current local time and TimezonePeriod
for the time zone as
an Array
. The first element is the time as a TimeWithOffset
. The
second element is the period.
# File 'lib/tzinfo/timezone.rb', line 1008
def current_time_and_period period = nil local_time = Timestamp.for(Time.now) do |ts| period = period_for(ts) TimestampWithOffset.set_timezone_offset(ts, period.offset) end [local_time, period] end
#dst?(time = Time.now) ⇒ Boolean
# File 'lib/tzinfo/timezone.rb', line 1059
def dst?(time = Time.now) period_for(time).dst? end
#eql?(tz) ⇒ Boolean
# File 'lib/tzinfo/timezone.rb', line 1113
def eql?(tz) self == tz end
#friendly_identifier(skip_first_part = false) ⇒ String
Returns #identifier, modified to make it more readable. Set
skip_first_part
to omit the first part of the identifier (typically a
region name) where there is more than one part.
For example:
TZInfo::Timezone.get('Europe/Paris').friendly_identifier(false) #=> "Europe - Paris"
TZInfo::Timezone.get('Europe/Paris').friendly_identifier(true) #=> "Paris"
TZInfo::Timezone.get('America/Indiana/Knox').friendly_identifier(false) #=> "America - Knox, Indiana"
TZInfo::Timezone.get('America/Indiana/Knox').friendly_identifier(true) #=> "Knox, Indiana"
# File 'lib/tzinfo/timezone.rb', line 277
def friendly_identifier(skip_first_part = false) id = identifier id = id.encode(Encoding::UTF_8) unless id.encoding.ascii_compatible? parts = id.split('/') if parts.empty? # shouldn't happen identifier elsif parts.length == 1 parts[0] else prefix = skip_first_part ? nil : "#{parts[0]} - " parts = parts.drop(1).map do |part| part.gsub!(/_/, ' ') if part.index(/[a-z]/) # Missing a space if a lower case followed by an upper case and the # name isn't McXxxx. part.gsub!(/([^M][a-z])([A-Z])/, '\1 \2') part.gsub!(/([M][a-bd-z])([A-Z])/, '\1 \2') # Missing an apostrophe if two consecutive upper case characters. part.gsub!(/([A-Z])([A-Z])/, '\1\'\2') end part end "#{prefix}#{parts.reverse.join(', ')}" end end
#hash ⇒ Integer
# File 'lib/tzinfo/timezone.rb', line 1118
def hash identifier.hash end
#identifier ⇒ String
# File 'lib/tzinfo/timezone.rb', line 241
def identifier raise_unknown_timezone end
#inspect ⇒ String
# File 'lib/tzinfo/timezone.rb', line 259
def inspect "#<#{self.class}: #{identifier}>" end
#local_datetime(year, month = 1, day = 1, hour = 0, minute = 0, second = 0, sub_second = 0, dst = Timezone.default_dst) {|periods| ... } ⇒ DateTimeWithOffset
Creates a DateTime
object based on the given (Gregorian calendar) date
and time parameters. The parameters are interpreted as a local time in the
time zone. The result has the appropriate offset
and
timezone_offset.
Warning: There are time values that are not valid as local times in a time zone (for example, during the transition from standard time to daylight savings time). There are also time values that are ambiguous, occurring more than once with different offsets to UTC (for example, during the transition from daylight savings time to standard time).
In the first case (an invalid local time), a PeriodNotFound
exception
will be raised.
In the second case (more than one occurrence), an AmbiguousTime
exception will be raised unless the optional dst
parameter or block
handles the ambiguity.
If the ambiguity is due to a transition from daylight savings time to
standard time, the dst
parameter can be used to select whether the
daylight savings time or local time is used. For example, the following
code would raise an AmbiguousTime
exception:
tz = TZInfo::Timezone.get('America/New_York')
tz.local_datetime(2004,10,31,1,30,0,0)
Specifying dst = true
would return a Time
with a UTC offset of -4
hours and abbreviation EDT (Eastern Daylight Time). Specifying dst =
false
would return a Time
with a UTC offset of -5 hours and
abbreviation EST (Eastern Standard Time).
The dst
parameter will not be able to resolve an ambiguity resulting
from the clocks being set back without changing from daylight savings time
to standard time. In this case, if a block is specified, it will be called
to resolve the ambiguity. The block must take a single parameter - an
Array
of TimezonePeriod
s that need to be resolved. The block can
select and return a single TimezonePeriod
or return nil
or an empty
Array
to cause an AmbiguousTime
exception to be raised.
The default value of the dst
parameter can be specified using
.default_dst=.
values, interpreted as a local time in the time zone.
# File 'lib/tzinfo/timezone.rb', line 831
def local_datetime(year, month = 1, day = 1, hour = 0, minute = 0, second = 0, sub_second = 0, dst = Timezone.default_dst, &block) (year, month, day, hour, minute, second, sub_second, dst, &block).to_datetime end
#local_time(year, month = 1, day = 1, hour = 0, minute = 0, second = 0, sub_second = 0, dst = Timezone.default_dst) {|periods| ... } ⇒ TimeWithOffset
Creates a Time
object based on the given (Gregorian calendar) date and
time parameters. The parameters are interpreted as a local time in the
time zone. The result has the appropriate #utc_offset, zone
and
timezone_offset.
Warning: There are time values that are not valid as local times in a time zone (for example, during the transition from standard time to daylight savings time). There are also time values that are ambiguous, occurring more than once with different offsets to UTC (for example, during the transition from daylight savings time to standard time).
In the first case (an invalid local time), a PeriodNotFound
exception
will be raised.
In the second case (more than one occurrence), an AmbiguousTime
exception will be raised unless the optional dst
parameter or block
handles the ambiguity.
If the ambiguity is due to a transition from daylight savings time to
standard time, the dst
parameter can be used to select whether the
daylight savings time or local time is used. For example, the following
code would raise an AmbiguousTime
exception:
tz = TZInfo::Timezone.get('America/New_York')
tz.local_time(2004,10,31,1,30,0,0)
Specifying dst = true
would return a Time
with a UTC offset of -4
hours and abbreviation EDT (Eastern Daylight Time). Specifying dst =
false
would return a Time
with a UTC offset of -5 hours and
abbreviation EST (Eastern Standard Time).
The dst
parameter will not be able to resolve an ambiguity resulting
from the clocks being set back without changing from daylight savings time
to standard time. In this case, if a block is specified, it will be called
to resolve the ambiguity. The block must take a single parameter - an
Array
of TimezonePeriod
s that need to be resolved. The block can
select and return a single TimezonePeriod
or return nil
or an empty
Array
to cause an AmbiguousTime
exception to be raised.
The default value of the dst
parameter can be specified using
.default_dst=.
# File 'lib/tzinfo/timezone.rb', line 743
def local_time(year, month = 1, day = 1, hour = 0, minute = 0, second = 0, sub_second = 0, dst = Timezone.default_dst, &block) (year, month, day, hour, minute, second, sub_second, dst, &block).to_time end
#local_timestamp(year, month = 1, day = 1, hour = 0, minute = 0, second = 0, sub_second = 0, dst = Timezone.default_dst) {|periods| ... } ⇒ TimestampWithOffset
Creates a Timestamp
object based on the given (Gregorian calendar) date
and time parameters. The parameters are interpreted as a local time in the
time zone. The result has the appropriate utc_offset and timezone_offset.
Warning: There are time values that are not valid as local times in a time zone (for example, during the transition from standard time to daylight savings time). There are also time values that are ambiguous, occurring more than once with different offsets to UTC (for example, during the transition from daylight savings time to standard time).
In the first case (an invalid local time), a PeriodNotFound
exception
will be raised.
In the second case (more than one occurrence), an AmbiguousTime
exception will be raised unless the optional dst
parameter or block
handles the ambiguity.
If the ambiguity is due to a transition from daylight savings time to
standard time, the dst
parameter can be used to select whether the
daylight savings time or local time is used. For example, the following
code would raise an AmbiguousTime
exception:
tz = TZInfo::Timezone.get('America/New_York')
tz. (2004,10,31,1,30,0,0)
Specifying dst = true
would return a Time
with a UTC offset of -4
hours and abbreviation EDT (Eastern Daylight Time). Specifying dst =
false
would return a Time
with a UTC offset of -5 hours and
abbreviation EST (Eastern Standard Time).
The dst
parameter will not be able to resolve an ambiguity resulting
from the clocks being set back without changing from daylight savings time
to standard time. In this case, if a block is specified, it will be called
to resolve the ambiguity. The block must take a single parameter - an
Array
of TimezonePeriod
s that need to be resolved. The block can
select and return a single TimezonePeriod
or return nil
or an empty
Array
to cause an AmbiguousTime
exception to be raised.
The default value of the dst
parameter can be specified using
.default_dst=.
# File 'lib/tzinfo/timezone.rb', line 919
def (year, month = 1, day = 1, hour = 0, minute = 0, second = 0, sub_second = 0, dst = Timezone.default_dst, &block) ts = Timestamp.create(year, month, day, hour, minute, second, sub_second) timezone_offset = period_for_local(ts, dst, &block).offset utc_offset = timezone_offset.observed_utc_offset TimestampWithOffset.new(ts.value - utc_offset, sub_second, utc_offset).set_timezone_offset(timezone_offset) end
#local_to_utc(local_time, dst = Timezone.default_dst) {|periods| ... } ⇒ Object
Converts a local time for the time zone to UTC.
The result will either be a Time
, DateTime
or Timestamp
according to
the type of the #local_time parameter.
The UTC offset of the #local_time parameter is ignored (it is treated as
a time in the time zone represented by self
).
Warning: There are local times that have no equivalent UTC times (for example, during the transition from standard time to daylight savings time). There are also local times that have more than one UTC equivalent (for example, during the transition from daylight savings time to standard time).
In the first case (no equivalent UTC time), a PeriodNotFound
exception
will be raised.
In the second case (more than one equivalent UTC time), an AmbiguousTime
exception will be raised unless the optional dst
parameter or block
handles the ambiguity.
If the ambiguity is due to a transition from daylight savings time to
standard time, the dst
parameter can be used to select whether the
daylight savings time or local time is used. For example, the following
code would raise an AmbiguousTime
exception:
tz = TZInfo::Timezone.get('America/New_York')
tz.period_for_local(Time.new(2004,10,31,1,30,0))
Specifying dst = true
would select the daylight savings period from
April to October 2004. Specifying dst = false
would return the
standard time period from October 2004 to April 2005.
The dst
parameter will not be able to resolve an ambiguity resulting
from the clocks being set back without changing from daylight savings time
to standard time. In this case, if a block is specified, it will be called
to resolve the ambiguity. The block must take a single parameter - an
Array
of TimezonePeriod
s that need to be resolved. The block can
select and return a single TimezonePeriod
or return nil
or an empty
Array
to cause an AmbiguousTime
exception to be raised.
The default value of the dst
parameter can be specified using
.default_dst=.
# File 'lib/tzinfo/timezone.rb', line 645
def local_to_utc(local_time, dst = Timezone.default_dst) raise ArgumentError, 'local_time must be specified' unless local_time Timestamp.for(local_time, :ignore) do |ts| period = if block_given? period_for_local(ts, dst) {|periods| yield periods } else period_for_local(ts, dst) end ts.add_and_set_utc_offset(-period.observed_utc_offset, :utc) end end
#name ⇒ String
# File 'lib/tzinfo/timezone.rb', line 247
def name # Don't use alias, as identifier gets overridden. identifier end
#now ⇒ TimeWithOffset
# File 'lib/tzinfo/timezone.rb', line 992
def now to_local(Time.now) end
#observed_utc_offset(time = Time.now) ⇒ Integer
Also known as: #utc_offset
Returns the observed offset from UTC in seconds at the given time. This includes adjustments made for daylight savings time.
# File 'lib/tzinfo/timezone.rb', line 1094
def observed_utc_offset(time = Time.now) period_for(time).observed_utc_offset end
#offsets_up_to(to, from = nil) ⇒ Array
<TimezoneOffsets
>
Returns the unique offsets used by the time zone up to a given time (to
)
as an Array
of TimezoneOffset
instances.
A from time may also be supplied using the from
parameter. If from is
not nil
, only offsets used from that time onwards will be returned.
Comparisons with to
are exclusive. Comparisons with from
are
inclusive.
# File 'lib/tzinfo/timezone.rb', line 947
def offsets_up_to(to, from = nil) raise ArgumentError, 'to must be specified' unless to = Timestamp.for(to) = from && Timestamp.for(from) transitions = transitions_up_to(, ) if transitions.empty? # No transitions in the range, find the period that covers it. if # Use the from date as it is inclusive. period = period_for( ) else # to is exclusive, so this can't be used with period_for. However, any # time earlier than to can be used. Subtract 1 hour. period = period_for( .add_and_set_utc_offset(-3600, :utc)) end [period.offset] else result = Set.new first = transitions.first result << first.previous_offset unless && first.at == transitions.each do |t| result << t.offset end result.to_a end end
#period_for(time) ⇒ TimezonePeriod
Returns the TimezonePeriod
that is valid at a given time.
Unlike #period_for_local and #period_for_utc, the UTC offset of the
time
parameter is taken into consideration.
# File 'lib/tzinfo/timezone.rb', line 319
def period_for(time) raise_unknown_timezone end
#period_for_local(local_time, dst = Timezone.default_dst) {|periods| ... } ⇒ TimezonePeriod
Returns the TimezonePeriod
that is valid at the given local time.
The UTC offset of the #local_time parameter is ignored (it is treated as
a time in the time zone represented by self
). Use the #period_for
method instead if the the UTC offset of the time needs to be taken into
consideration.
Warning: There are local times that have no equivalent UTC times (for example, during the transition from standard time to daylight savings time). There are also local times that have more than one UTC equivalent (for example, during the transition from daylight savings time to standard time).
In the first case (no equivalent UTC time), a PeriodNotFound
exception
will be raised.
In the second case (more than one equivalent UTC time), an AmbiguousTime
exception will be raised unless the optional dst
parameter or block
handles the ambiguity.
If the ambiguity is due to a transition from daylight savings time to
standard time, the dst
parameter can be used to select whether the
daylight savings time or local time is used. For example, the following
code would raise an AmbiguousTime
exception:
tz = TZInfo::Timezone.get('America/New_York')
tz.period_for_local(Time.new(2004,10,31,1,30,0))
Specifying dst = true
would select the daylight savings period from
April to October 2004. Specifying dst = false
would return the
standard time period from October 2004 to April 2005.
The dst
parameter will not be able to resolve an ambiguity resulting
from the clocks being set back without changing from daylight savings time
to standard time. In this case, if a block is specified, it will be called
to resolve the ambiguity. The block must take a single parameter - an
Array
of TimezonePeriod
s that need to be resolved. The block can
select and return a single TimezonePeriod
or return nil
or an empty
Array
to cause an AmbiguousTime
exception to be raised.
The default value of the dst
parameter can be specified using
.default_dst=.
# File 'lib/tzinfo/timezone.rb', line 494
def period_for_local(local_time, dst = Timezone.default_dst) raise ArgumentError, 'local_time must be specified' unless local_time local_time = Timestamp.for(local_time, :ignore) results = periods_for_local(local_time) if results.empty? raise PeriodNotFound, "#{local_time.strftime('%Y-%m-%d %H:%M:%S')} is an invalid local time." elsif results.size < 2 results.first else # ambiguous result try to resolve if !dst.nil? matches = results.find_all {|period| period.dst? == dst} results = matches if !matches.empty? end if results.size < 2 results.first else # still ambiguous, try the block if block_given? results = yield results end if results.is_a?(TimezonePeriod) results elsif results && results.size == 1 results.first else raise AmbiguousTime, "#{local_time.strftime('%Y-%m-%d %H:%M:%S')} is an ambiguous local time." end end end end
#period_for_utc(utc_time) ⇒ TimezonePeriod
Returns the TimezonePeriod
that is valid at a given time.
The UTC offset of the utc_time
parameter is ignored (it is treated as a
UTC time). Use the #period_for method instead if the UTC offset of the
time needs to be taken into consideration.
# File 'lib/tzinfo/timezone.rb', line 425
def period_for_utc(utc_time) raise ArgumentError, 'utc_time must be specified' unless utc_time period_for(Timestamp.for(utc_time, :treat_as_utc)) end
#periods_for_local(local_time) ⇒ Array
<TimezonePeriod>
Returns the set of TimezonePeriod
s that are valid for the given
local time as an Array
.
The UTC offset of the #local_time parameter is ignored (it is treated as
a time in the time zone represented by self
).
This will typically return an Array
containing a single
TimezonePeriod
. More than one TimezonePeriod
will be returned when the
local time is ambiguous (for example, when daylight savings time ends). An
empty Array
will be returned when the local time is not valid (for
example, when daylight savings time begins).
To obtain just a single TimezonePeriod
in all cases, use
#period_for_local instead and specify how ambiguities should be resolved.
# File 'lib/tzinfo/timezone.rb', line 342
def periods_for_local(local_time) raise_unknown_timezone end
#raise_unknown_timezone (private)
Raises an UnknownTimezone
exception.
# File 'lib/tzinfo/timezone.rb', line 1156
def raise_unknown_timezone raise UnknownTimezone, 'TZInfo::Timezone should not be constructed directly (use TZInfo::Timezone.get instead)' end
#strftime(format, time = Time.now) ⇒ String
Converts a time to local time for the time zone and returns a String
representation of the local time according to the given format.
#strftime
first expands any occurrences of %Z
in the format
string to the time zone abbreviation for the local time (for example, EST
or EDT). Depending on the type of time
parameter, the result of the
expansion is then passed to either Time#strftime
, DateTime#strftime
or
Timestamp#strftime to handle any other format directives.
This method is equivalent to the following:
time_zone.to_local(time).strftime(format)
#to_local(time) ⇒ Object
Converts a time to the local time for the time zone.
The result will be of type TimeWithOffset
(if passed a Time
),
DateTimeWithOffset
(if passed a DateTime
) or TimestampWithOffset
(if
passed a Timestamp
). TimeWithOffset
, DateTimeWithOffset
and
TimestampWithOffset
are subclasses of Time
, DateTime
and Timestamp
that provide additional information about the local result.
Unlike #utc_to_local, to_local
takes the UTC offset of the given time
into consideration.
# File 'lib/tzinfo/timezone.rb', line 548
def to_local(time) raise ArgumentError, 'time must be specified' unless time Timestamp.for(time) do |ts| TimestampWithOffset.set_timezone_offset(ts, period_for(ts).offset) end end
#to_s ⇒ String
# File 'lib/tzinfo/timezone.rb', line 253
def to_s friendly_identifier end
#transitions_up_to(to, from = nil) ⇒ Array
<TimezoneTransition>
Returns an Array
of TimezoneTransition
instances representing the
times where the UTC offset of the timezone changes.
Transitions are returned up to a given time (to
).
A from time may also be supplied using the from
parameter. If from is
not nil
, only transitions from that time onwards will be returned.
Comparisons with to
are exclusive. Comparisons with from
are
inclusive. If a transition falls precisely on to
, it will be excluded.
If a transition falls on from
, it will be included.
# File 'lib/tzinfo/timezone.rb', line 370
def transitions_up_to(to, from = nil) raise_unknown_timezone end
#utc_offset(time = Time.now)
Alias for #observed_utc_offset.
# File 'lib/tzinfo/timezone.rb', line 1097
alias utc_offset observed_utc_offset
#utc_to_local(utc_time) ⇒ Object
Converts a time in UTC to the local time for the time zone.
The result will be of type TimeWithOffset
(if passed a Time
),
DateTimeWithOffset
(if passed a DateTime
) or TimestampWithOffset
(if
passed a Timestamp
). TimeWithOffset
, DateTimeWithOffset
and
TimestampWithOffset
are subclasses of Time
, DateTime
and Timestamp
that provide additional information about the local result.
The UTC offset of the utc_time
parameter is ignored (it is treated as a
UTC time). Use the #to_local method instead if the the UTC offset of the
time needs to be taken into consideration.