Class: TZInfo::Timezone Abstract
- Inherits:
-
Object
- Object
- TZInfo::Timezone
- Includes:
- Comparable
- Defined in:
- lib/tzinfo/timezone.rb
Overview
The Timezone.get method returns an instance of either DataTimezone or LinkedTimezone. The Timezone.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, Timezone.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.
Direct Known Subclasses
Class Method Summary collapse
- ._load(data) ⇒ Timezone
-
.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 one Country. -
.all_country_zones ⇒ Array<Timezone>
Returns an
Array
of all the time zones that are observed by at least one Country. -
.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>
An
Array
containing the identifiers of all the available time zones. -
.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. -
.default_dst ⇒ Boolean
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) ⇒ Object
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. -
.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.
Instance Method Summary collapse
-
#<=>(tz) ⇒ Integer
Compares this Timezone with another based on the #identifier.
-
#=~(regexp) ⇒ Integer
Matches
regexp
against the #identifier of this Timezone. -
#_dump(limit) ⇒ String
Returns a serialized representation of this Timezone.
-
#abbreviation(time = Time.now) ⇒ String
(also: #abbr)
The abbreviation of this Timezone at the given time.
-
#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
-
#current_period ⇒ TimezonePeriod
The current TimezonePeriod for the time zone.
-
#current_time_and_period ⇒ Array
(also: #current_period_and_time)
Returns the current local time and TimezonePeriod for the time zone as an
Array
. -
#dst?(time = Time.now) ⇒ Boolean
Whether daylight savings time is in effect at the given time.
-
#eql?(tz) ⇒ Boolean
true
iftz
is an instance of Timezone and has the same #identifier asself
, otherwisefalse
. -
#friendly_identifier(skip_first_part = false) ⇒ String
Returns #identifier, modified to make it more readable.
-
#hash ⇒ Integer
A hash based on the #identifier.
-
#identifier ⇒ String
The identifier of the time zone, for example,
"Europe/Paris"
. -
#inspect ⇒ String
The internal object state as a programmer-readable
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
The identifier of the time zone, for example,
"Europe/Paris"
. -
#now ⇒ TimeWithOffset
The current local time in the time zone.
-
#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
of TimezoneOffset 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 TimezonePeriods that are valid for the given local time as an
Array
. -
#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
#identifier, modified to make it more readable.
-
#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. -
#utc_to_local(utc_time) ⇒ Object
Converts a time in UTC to the local time for the time zone.
Class Method Details
._load(data) ⇒ Timezone
Loads a TZInfo::Timezone from the serialized representation returned by #_dump.
This is method is called when using Marshal.load
or Marshal.restore
to restore a serialized TZInfo::Timezone.
1147 1148 1149 |
# 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.
TZInfo::TimezoneProxy instances are returned to avoid the overhead of loading time zone data until it is first needed.
151 152 153 |
# 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'
).
TZInfo::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.
219 220 221 |
# File 'lib/tzinfo/timezone.rb', line 219 def all_country_zone_identifiers Country.all.map(&:zone_identifiers).flatten.uniq end |
.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'
).
TZInfo::TimezoneProxy instances are returned to avoid the overhead of loading time zone data until it is first needed.
206 207 208 |
# File 'lib/tzinfo/timezone.rb', line 206 def all_country_zones Country.all.map(&:zones).flatten.uniq end |
.all_data_zone_identifiers ⇒ Array<String>
time zones that are defined by offsets and transitions.
175 176 177 |
# 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.
TZInfo::TimezoneProxy instances are returned to avoid the overhead of loading time zone data until it is first needed.
169 170 171 |
# File 'lib/tzinfo/timezone.rb', line 169 def all_data_zones get_proxies(all_data_zone_identifiers) end |
.all_identifiers ⇒ Array<String>
Returns an Array
containing the identifiers of all the
available time zones.
157 158 159 |
# 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.
193 194 195 |
# 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.
TZInfo::TimezoneProxy instances are returned to avoid the overhead of loading time zone data until it is first needed.
187 188 189 |
# File 'lib/tzinfo/timezone.rb', line 187 def all_linked_zones get_proxies(all_linked_zone_identifiers) end |
.default_dst ⇒ Boolean
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=.
110 111 112 |
# File 'lib/tzinfo/timezone.rb', line 110 def default_dst @@default_dst end |
.default_dst=(value) ⇒ Object
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
.
96 97 98 |
# File 'lib/tzinfo/timezone.rb', line 96 def default_dst=(value) @@default_dst = value.nil? ? nil : !!value 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 TZInfo::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).
127 128 129 |
# File 'lib/tzinfo/timezone.rb', line 127 def get(identifier) data_source.get_timezone_info(identifier).create_timezone 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.
141 142 143 |
# File 'lib/tzinfo/timezone.rb', line 141 def get_proxy(identifier) TimezoneProxy.new(identifier) end |
Instance Method Details
#<=>(tz) ⇒ Integer
Compares this TZInfo::Timezone with another based on the #identifier.
1105 1106 1107 1108 |
# 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 TZInfo::Timezone.
1128 1129 1130 |
# File 'lib/tzinfo/timezone.rb', line 1128 def =~(regexp) regexp =~ identifier end |
#_dump(limit) ⇒ String
Returns a serialized representation of this TZInfo::Timezone. This method is
called when using Marshal.dump
with an instance of TZInfo::Timezone.
1137 1138 1139 |
# File 'lib/tzinfo/timezone.rb', line 1137 def _dump(limit) identifier end |
#abbreviation(time = Time.now) ⇒ String Also known as: abbr
Returns the abbreviation of this TZInfo::Timezone at the given time.
1048 1049 1050 |
# 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.
1081 1082 1083 |
# 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.
987 988 989 |
# File 'lib/tzinfo/timezone.rb', line 987 def canonical_identifier canonical_zone.identifier end |
#canonical_zone ⇒ Timezone
Returns the canonical TZInfo::Timezone instance for this TZInfo::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 TZInfo::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.
412 413 414 |
# File 'lib/tzinfo/timezone.rb', line 412 def canonical_zone raise_unknown_timezone end |
#current_period ⇒ TimezonePeriod
Returns the current TZInfo::TimezonePeriod for the time zone.
997 998 999 |
# File 'lib/tzinfo/timezone.rb', line 997 def current_period period_for(Time.now) end |
#current_time_and_period ⇒ Array Also known as: current_period_and_time
Returns the current local time and TZInfo::TimezonePeriod for the time zone as
an Array
. The first element is the time as a TZInfo::TimeWithOffset. The
second element is the period.
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 |
# 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
Returns whether daylight savings time is in effect at the given time.
1059 1060 1061 |
# File 'lib/tzinfo/timezone.rb', line 1059 def dst?(time = Time.now) period_for(time).dst? end |
#eql?(tz) ⇒ Boolean
Returns true
if tz
is an instance of TZInfo::Timezone and has the
same #identifier as self
, otherwise false
.
1113 1114 1115 |
# 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"
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 |
# 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
Returns a hash based on the #identifier.
1118 1119 1120 |
# File 'lib/tzinfo/timezone.rb', line 1118 def hash identifier.hash end |
#identifier ⇒ String
Returns the identifier of the time zone, for example,
"Europe/Paris"
.
241 242 243 |
# File 'lib/tzinfo/timezone.rb', line 241 def identifier raise_unknown_timezone end |
#inspect ⇒ String
Returns the internal object state as a programmer-readable
String
.
259 260 261 |
# 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 TZInfo::TimezonePeriods that need to be resolved. The block can
select and return a single TZInfo::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.
831 832 833 |
# 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 TZInfo::TimezonePeriods that need to be resolved. The block can
select and return a single TZInfo::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=.
743 744 745 |
# 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 TZInfo::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 TZInfo::TimezonePeriods that need to be resolved. The block can
select and return a single TZInfo::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=.
919 920 921 922 923 924 |
# 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 TZInfo::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 TZInfo::TimezonePeriods that need to be resolved. The block can
select and return a single TZInfo::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=.
645 646 647 648 649 650 651 652 653 654 655 656 657 |
# 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
Returns the identifier of the time zone, for example,
"Europe/Paris"
.
247 248 249 250 |
# File 'lib/tzinfo/timezone.rb', line 247 def name # Don't use alias, as identifier gets overridden. identifier end |
#now ⇒ TimeWithOffset
Returns the current local time in the time zone.
992 993 994 |
# 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.
1094 1095 1096 |
# 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 TZInfo::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.
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 |
# 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 TZInfo::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.
319 320 321 |
# 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 TZInfo::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 TZInfo::TimezonePeriods that need to be resolved. The block can
select and return a single TZInfo::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=.
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 |
# 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 TZInfo::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.
425 426 427 428 |
# 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 TZInfo::TimezonePeriods 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
TZInfo::TimezonePeriod. More than one TZInfo::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 TZInfo::TimezonePeriod in all cases, use #period_for_local instead and specify how ambiguities should be resolved.
342 343 344 |
# File 'lib/tzinfo/timezone.rb', line 342 def periods_for_local(local_time) raise_unknown_timezone 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.
Timezone#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)
1039 1040 1041 |
# File 'lib/tzinfo/timezone.rb', line 1039 def strftime(format, time = Time.now) to_local(time).strftime(format) end |
#to_local(time) ⇒ Object
Converts a time to the local time for the time zone.
The result will be of type TZInfo::TimeWithOffset (if passed a Time
),
DateTimeWithOffset (if passed a DateTime
) or TZInfo::TimestampWithOffset (if
passed a TZInfo::Timestamp). TZInfo::TimeWithOffset, DateTimeWithOffset and
TZInfo::TimestampWithOffset are subclasses of Time
, DateTime
and TZInfo::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.
548 549 550 551 552 553 554 |
# 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
Returns #identifier, modified to make it more readable.
253 254 255 |
# 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 TZInfo::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.
370 371 372 |
# File 'lib/tzinfo/timezone.rb', line 370 def transitions_up_to(to, from = nil) raise_unknown_timezone end |
#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 TZInfo::TimeWithOffset (if passed a Time
),
DateTimeWithOffset (if passed a DateTime
) or TZInfo::TimestampWithOffset (if
passed a TZInfo::Timestamp). TZInfo::TimeWithOffset, DateTimeWithOffset and
TZInfo::TimestampWithOffset are subclasses of Time
, DateTime
and TZInfo::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.
572 573 574 575 576 577 578 |
# File 'lib/tzinfo/timezone.rb', line 572 def utc_to_local(utc_time) raise ArgumentError, 'utc_time must be specified' unless utc_time Timestamp.for(utc_time, :treat_as_utc) do |ts| to_local(ts) end end |