1 // Copyright 2016 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // A library for translating between absolute times (represented by
16 // std::chrono::time_points of the std::chrono::system_clock) and civil
17 // times (represented by cctz::civil_second) using the rules defined by
18 // a time zone (cctz::time_zone).
19
20 #ifndef ABSL_TIME_INTERNAL_CCTZ_TIME_ZONE_H_
21 #define ABSL_TIME_INTERNAL_CCTZ_TIME_ZONE_H_
22
23 #include <chrono>
24 #include <cstdint>
25 #include <string>
26 #include <utility>
27
28 #include "absl/base/config.h"
29 #include "absl/time/internal/cctz/include/cctz/civil_time.h"
30
31 namespace absl {
32 ABSL_NAMESPACE_BEGIN
33 namespace time_internal {
34 namespace cctz {
35
36 // Convenience aliases. Not intended as public API points.
37 template <typename D>
38 using time_point = std::chrono::time_point<std::chrono::system_clock, D>;
39 using seconds = std::chrono::duration<std::int_fast64_t>;
40 using sys_seconds = seconds; // Deprecated. Use cctz::seconds instead.
41
42 namespace detail {
43 template <typename D>
split_seconds(const time_point<D> & tp)44 inline std::pair<time_point<seconds>, D> split_seconds(
45 const time_point<D>& tp) {
46 auto sec = std::chrono::time_point_cast<seconds>(tp);
47 auto sub = tp - sec;
48 if (sub.count() < 0) {
49 sec -= seconds(1);
50 sub += seconds(1);
51 }
52 return {sec, std::chrono::duration_cast<D>(sub)};
53 }
split_seconds(const time_point<seconds> & tp)54 inline std::pair<time_point<seconds>, seconds> split_seconds(
55 const time_point<seconds>& tp) {
56 return {tp, seconds::zero()};
57 }
58 } // namespace detail
59
60 // cctz::time_zone is an opaque, small, value-type class representing a
61 // geo-political region within which particular rules are used for mapping
62 // between absolute and civil times. Time zones are named using the TZ
63 // identifiers from the IANA Time Zone Database, such as "America/Los_Angeles"
64 // or "Australia/Sydney". Time zones are created from factory functions such
65 // as load_time_zone(). Note: strings like "PST" and "EDT" are not valid TZ
66 // identifiers.
67 //
68 // Example:
69 // cctz::time_zone utc = cctz::utc_time_zone();
70 // cctz::time_zone pst = cctz::fixed_time_zone(std::chrono::hours(-8));
71 // cctz::time_zone loc = cctz::local_time_zone();
72 // cctz::time_zone lax;
73 // if (!cctz::load_time_zone("America/Los_Angeles", &lax)) { ... }
74 //
75 // See also:
76 // - http://www.iana.org/time-zones
77 // - https://en.wikipedia.org/wiki/Zoneinfo
78 class time_zone {
79 public:
time_zone()80 time_zone() : time_zone(nullptr) {} // Equivalent to UTC
81 time_zone(const time_zone&) = default;
82 time_zone& operator=(const time_zone&) = default;
83
84 std::string name() const;
85
86 // An absolute_lookup represents the civil time (cctz::civil_second) within
87 // this time_zone at the given absolute time (time_point). There are
88 // additionally a few other fields that may be useful when working with
89 // older APIs, such as std::tm.
90 //
91 // Example:
92 // const cctz::time_zone tz = ...
93 // const auto tp = std::chrono::system_clock::now();
94 // const cctz::time_zone::absolute_lookup al = tz.lookup(tp);
95 struct absolute_lookup {
96 civil_second cs;
97 // Note: The following fields exist for backward compatibility with older
98 // APIs. Accessing these fields directly is a sign of imprudent logic in
99 // the calling code. Modern time-related code should only access this data
100 // indirectly by way of cctz::format().
101 int offset; // civil seconds east of UTC
102 bool is_dst; // is offset non-standard?
103 const char* abbr; // time-zone abbreviation (e.g., "PST")
104 };
105 absolute_lookup lookup(const time_point<seconds>& tp) const;
106 template <typename D>
lookup(const time_point<D> & tp)107 absolute_lookup lookup(const time_point<D>& tp) const {
108 return lookup(detail::split_seconds(tp).first);
109 }
110
111 // A civil_lookup represents the absolute time(s) (time_point) that
112 // correspond to the given civil time (cctz::civil_second) within this
113 // time_zone. Usually the given civil time represents a unique instant
114 // in time, in which case the conversion is unambiguous. However,
115 // within this time zone, the given civil time may be skipped (e.g.,
116 // during a positive UTC offset shift), or repeated (e.g., during a
117 // negative UTC offset shift). To account for these possibilities,
118 // civil_lookup is richer than just a single time_point.
119 //
120 // In all cases the civil_lookup::kind enum will indicate the nature
121 // of the given civil-time argument, and the pre, trans, and post
122 // members will give the absolute time answers using the pre-transition
123 // offset, the transition point itself, and the post-transition offset,
124 // respectively (all three times are equal if kind == UNIQUE). If any
125 // of these three absolute times is outside the representable range of a
126 // time_point<seconds> the field is set to its maximum/minimum value.
127 //
128 // Example:
129 // cctz::time_zone lax;
130 // if (!cctz::load_time_zone("America/Los_Angeles", &lax)) { ... }
131 //
132 // // A unique civil time.
133 // auto jan01 = lax.lookup(cctz::civil_second(2011, 1, 1, 0, 0, 0));
134 // // jan01.kind == cctz::time_zone::civil_lookup::UNIQUE
135 // // jan01.pre is 2011/01/01 00:00:00 -0800
136 // // jan01.trans is 2011/01/01 00:00:00 -0800
137 // // jan01.post is 2011/01/01 00:00:00 -0800
138 //
139 // // A Spring DST transition, when there is a gap in civil time.
140 // auto mar13 = lax.lookup(cctz::civil_second(2011, 3, 13, 2, 15, 0));
141 // // mar13.kind == cctz::time_zone::civil_lookup::SKIPPED
142 // // mar13.pre is 2011/03/13 03:15:00 -0700
143 // // mar13.trans is 2011/03/13 03:00:00 -0700
144 // // mar13.post is 2011/03/13 01:15:00 -0800
145 //
146 // // A Fall DST transition, when civil times are repeated.
147 // auto nov06 = lax.lookup(cctz::civil_second(2011, 11, 6, 1, 15, 0));
148 // // nov06.kind == cctz::time_zone::civil_lookup::REPEATED
149 // // nov06.pre is 2011/11/06 01:15:00 -0700
150 // // nov06.trans is 2011/11/06 01:00:00 -0800
151 // // nov06.post is 2011/11/06 01:15:00 -0800
152 struct civil_lookup {
153 enum civil_kind {
154 UNIQUE, // the civil time was singular (pre == trans == post)
155 SKIPPED, // the civil time did not exist (pre >= trans > post)
156 REPEATED, // the civil time was ambiguous (pre < trans <= post)
157 } kind;
158 time_point<seconds> pre; // uses the pre-transition offset
159 time_point<seconds> trans; // instant of civil-offset change
160 time_point<seconds> post; // uses the post-transition offset
161 };
162 civil_lookup lookup(const civil_second& cs) const;
163
164 // Finds the time of the next/previous offset change in this time zone.
165 //
166 // By definition, next_transition(tp, &trans) returns false when tp has
167 // its maximum value, and prev_transition(tp, &trans) returns false
168 // when tp has its minimum value. If the zone has no transitions, the
169 // result will also be false no matter what the argument.
170 //
171 // Otherwise, when tp has its minimum value, next_transition(tp, &trans)
172 // returns true and sets trans to the first recorded transition. Chains
173 // of calls to next_transition()/prev_transition() will eventually return
174 // false, but it is unspecified exactly when next_transition(tp, &trans)
175 // jumps to false, or what time is set by prev_transition(tp, &trans) for
176 // a very distant tp.
177 //
178 // Note: Enumeration of time-zone transitions is for informational purposes
179 // only. Modern time-related code should not care about when offset changes
180 // occur.
181 //
182 // Example:
183 // cctz::time_zone nyc;
184 // if (!cctz::load_time_zone("America/New_York", &nyc)) { ... }
185 // const auto now = std::chrono::system_clock::now();
186 // auto tp = cctz::time_point<cctz::seconds>::min();
187 // cctz::time_zone::civil_transition trans;
188 // while (tp <= now && nyc.next_transition(tp, &trans)) {
189 // // transition: trans.from -> trans.to
190 // tp = nyc.lookup(trans.to).trans;
191 // }
192 struct civil_transition {
193 civil_second from; // the civil time we jump from
194 civil_second to; // the civil time we jump to
195 };
196 bool next_transition(const time_point<seconds>& tp,
197 civil_transition* trans) const;
198 template <typename D>
next_transition(const time_point<D> & tp,civil_transition * trans)199 bool next_transition(const time_point<D>& tp, civil_transition* trans) const {
200 return next_transition(detail::split_seconds(tp).first, trans);
201 }
202 bool prev_transition(const time_point<seconds>& tp,
203 civil_transition* trans) const;
204 template <typename D>
prev_transition(const time_point<D> & tp,civil_transition * trans)205 bool prev_transition(const time_point<D>& tp, civil_transition* trans) const {
206 return prev_transition(detail::split_seconds(tp).first, trans);
207 }
208
209 // version() and description() provide additional information about the
210 // time zone. The content of each of the returned strings is unspecified,
211 // however, when the IANA Time Zone Database is the underlying data source
212 // the version() std::string will be in the familar form (e.g, "2018e") or
213 // empty when unavailable.
214 //
215 // Note: These functions are for informational or testing purposes only.
216 std::string version() const; // empty when unknown
217 std::string description() const;
218
219 // Relational operators.
220 friend bool operator==(time_zone lhs, time_zone rhs) {
221 return &lhs.effective_impl() == &rhs.effective_impl();
222 }
223 friend bool operator!=(time_zone lhs, time_zone rhs) { return !(lhs == rhs); }
224
225 template <typename H>
AbslHashValue(H h,time_zone tz)226 friend H AbslHashValue(H h, time_zone tz) {
227 return H::combine(std::move(h), &tz.effective_impl());
228 }
229
230 class Impl;
231
232 private:
time_zone(const Impl * impl)233 explicit time_zone(const Impl* impl) : impl_(impl) {}
234 const Impl& effective_impl() const; // handles implicit UTC
235 const Impl* impl_;
236 };
237
238 // Loads the named time zone. May perform I/O on the initial load.
239 // If the name is invalid, or some other kind of error occurs, returns
240 // false and "*tz" is set to the UTC time zone.
241 bool load_time_zone(const std::string& name, time_zone* tz);
242
243 // Returns a time_zone representing UTC. Cannot fail.
244 time_zone utc_time_zone();
245
246 // Returns a time zone that is a fixed offset (seconds east) from UTC.
247 // Note: If the absolute value of the offset is greater than 24 hours
248 // you'll get UTC (i.e., zero offset) instead.
249 time_zone fixed_time_zone(const seconds& offset);
250
251 // Returns a time zone representing the local time zone. Falls back to UTC.
252 // Note: local_time_zone.name() may only be something like "localtime".
253 time_zone local_time_zone();
254
255 // Returns the civil time (cctz::civil_second) within the given time zone at
256 // the given absolute time (time_point). Since the additional fields provided
257 // by the time_zone::absolute_lookup struct should rarely be needed in modern
258 // code, this convert() function is simpler and should be preferred.
259 template <typename D>
convert(const time_point<D> & tp,const time_zone & tz)260 inline civil_second convert(const time_point<D>& tp, const time_zone& tz) {
261 return tz.lookup(tp).cs;
262 }
263
264 // Returns the absolute time (time_point) that corresponds to the given civil
265 // time within the given time zone. If the civil time is not unique (i.e., if
266 // it was either repeated or non-existent), then the returned time_point is
267 // the best estimate that preserves relative order. That is, this function
268 // guarantees that if cs1 < cs2, then convert(cs1, tz) <= convert(cs2, tz).
convert(const civil_second & cs,const time_zone & tz)269 inline time_point<seconds> convert(const civil_second& cs,
270 const time_zone& tz) {
271 const time_zone::civil_lookup cl = tz.lookup(cs);
272 if (cl.kind == time_zone::civil_lookup::SKIPPED) return cl.trans;
273 return cl.pre;
274 }
275
276 namespace detail {
277 using femtoseconds = std::chrono::duration<std::int_fast64_t, std::femto>;
278 std::string format(const std::string&, const time_point<seconds>&,
279 const femtoseconds&, const time_zone&);
280 bool parse(const std::string&, const std::string&, const time_zone&,
281 time_point<seconds>*, femtoseconds*, std::string* err = nullptr);
282 } // namespace detail
283
284 // Formats the given time_point in the given cctz::time_zone according to
285 // the provided format string. Uses strftime()-like formatting options,
286 // with the following extensions:
287 //
288 // - %Ez - RFC3339-compatible numeric UTC offset (+hh:mm or -hh:mm)
289 // - %E*z - Full-resolution numeric UTC offset (+hh:mm:ss or -hh:mm:ss)
290 // - %E#S - Seconds with # digits of fractional precision
291 // - %E*S - Seconds with full fractional precision (a literal '*')
292 // - %E#f - Fractional seconds with # digits of precision
293 // - %E*f - Fractional seconds with full precision (a literal '*')
294 // - %E4Y - Four-character years (-999 ... -001, 0000, 0001 ... 9999)
295 //
296 // Note that %E0S behaves like %S, and %E0f produces no characters. In
297 // contrast %E*f always produces at least one digit, which may be '0'.
298 //
299 // Note that %Y produces as many characters as it takes to fully render the
300 // year. A year outside of [-999:9999] when formatted with %E4Y will produce
301 // more than four characters, just like %Y.
302 //
303 // Tip: Format strings should include the UTC offset (e.g., %z, %Ez, or %E*z)
304 // so that the resulting string uniquely identifies an absolute time.
305 //
306 // Example:
307 // cctz::time_zone lax;
308 // if (!cctz::load_time_zone("America/Los_Angeles", &lax)) { ... }
309 // auto tp = cctz::convert(cctz::civil_second(2013, 1, 2, 3, 4, 5), lax);
310 // std::string f = cctz::format("%H:%M:%S", tp, lax); // "03:04:05"
311 // f = cctz::format("%H:%M:%E3S", tp, lax); // "03:04:05.000"
312 template <typename D>
format(const std::string & fmt,const time_point<D> & tp,const time_zone & tz)313 inline std::string format(const std::string& fmt, const time_point<D>& tp,
314 const time_zone& tz) {
315 const auto p = detail::split_seconds(tp);
316 const auto n = std::chrono::duration_cast<detail::femtoseconds>(p.second);
317 return detail::format(fmt, p.first, n, tz);
318 }
319
320 // Parses an input string according to the provided format string and
321 // returns the corresponding time_point. Uses strftime()-like formatting
322 // options, with the same extensions as cctz::format(), but with the
323 // exceptions that %E#S is interpreted as %E*S, and %E#f as %E*f. %Ez
324 // and %E*z also accept the same inputs.
325 //
326 // %Y consumes as many numeric characters as it can, so the matching data
327 // should always be terminated with a non-numeric. %E4Y always consumes
328 // exactly four characters, including any sign.
329 //
330 // Unspecified fields are taken from the default date and time of ...
331 //
332 // "1970-01-01 00:00:00.0 +0000"
333 //
334 // For example, parsing a string of "15:45" (%H:%M) will return a time_point
335 // that represents "1970-01-01 15:45:00.0 +0000".
336 //
337 // Note that parse() returns time instants, so it makes most sense to parse
338 // fully-specified date/time strings that include a UTC offset (%z, %Ez, or
339 // %E*z).
340 //
341 // Note also that parse() only heeds the fields year, month, day, hour,
342 // minute, (fractional) second, and UTC offset. Other fields, like weekday (%a
343 // or %A), while parsed for syntactic validity, are ignored in the conversion.
344 //
345 // Date and time fields that are out-of-range will be treated as errors rather
346 // than normalizing them like cctz::civil_second() would do. For example, it
347 // is an error to parse the date "Oct 32, 2013" because 32 is out of range.
348 //
349 // A second of ":60" is normalized to ":00" of the following minute with
350 // fractional seconds discarded. The following table shows how the given
351 // seconds and subseconds will be parsed:
352 //
353 // "59.x" -> 59.x // exact
354 // "60.x" -> 00.0 // normalized
355 // "00.x" -> 00.x // exact
356 //
357 // Errors are indicated by returning false.
358 //
359 // Example:
360 // const cctz::time_zone tz = ...
361 // std::chrono::system_clock::time_point tp;
362 // if (cctz::parse("%Y-%m-%d", "2015-10-09", tz, &tp)) {
363 // ...
364 // }
365 template <typename D>
parse(const std::string & fmt,const std::string & input,const time_zone & tz,time_point<D> * tpp)366 inline bool parse(const std::string& fmt, const std::string& input,
367 const time_zone& tz, time_point<D>* tpp) {
368 time_point<seconds> sec;
369 detail::femtoseconds fs;
370 const bool b = detail::parse(fmt, input, tz, &sec, &fs);
371 if (b) {
372 // TODO: Return false if unrepresentable as a time_point<D>.
373 *tpp = std::chrono::time_point_cast<D>(sec);
374 *tpp += std::chrono::duration_cast<D>(fs);
375 }
376 return b;
377 }
378
379 } // namespace cctz
380 } // namespace time_internal
381 ABSL_NAMESPACE_END
382 } // namespace absl
383
384 #endif // ABSL_TIME_INTERNAL_CCTZ_TIME_ZONE_H_
385