1 // Copyright 2018 The Abseil Authors.
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 // -----------------------------------------------------------------------------
16 // File: civil_time.h
17 // -----------------------------------------------------------------------------
18 //
19 // This header file defines abstractions for computing with "civil time".
20 // The term "civil time" refers to the legally recognized human-scale time
21 // that is represented by the six fields `YYYY-MM-DD hh:mm:ss`. A "date"
22 // is perhaps the most common example of a civil time (represented here as
23 // an `absl::CivilDay`).
24 //
25 // Modern-day civil time follows the Gregorian Calendar and is a
26 // time-zone-independent concept: a civil time of "2015-06-01 12:00:00", for
27 // example, is not tied to a time zone. Put another way, a civil time does not
28 // map to a unique point in time; a civil time must be mapped to an absolute
29 // time *through* a time zone.
30 //
31 // Because a civil time is what most people think of as "time," it is common to
32 // map absolute times to civil times to present to users.
33 //
34 // Time zones define the relationship between absolute and civil times. Given an
35 // absolute or civil time and a time zone, you can compute the other time:
36 //
37 // Civil Time = F(Absolute Time, Time Zone)
38 // Absolute Time = G(Civil Time, Time Zone)
39 //
40 // The Abseil time library allows you to construct such civil times from
41 // absolute times; consult time.h for such functionality.
42 //
43 // This library provides six classes for constructing civil-time objects, and
44 // provides several helper functions for rounding, iterating, and performing
45 // arithmetic on civil-time objects, while avoiding complications like
46 // daylight-saving time (DST):
47 //
48 // * `absl::CivilSecond`
49 // * `absl::CivilMinute`
50 // * `absl::CivilHour`
51 // * `absl::CivilDay`
52 // * `absl::CivilMonth`
53 // * `absl::CivilYear`
54 //
55 // Example:
56 //
57 // // Construct a civil-time object for a specific day
58 // const absl::CivilDay cd(1969, 07, 20);
59 //
60 // // Construct a civil-time object for a specific second
61 // const absl::CivilSecond cd(2018, 8, 1, 12, 0, 1);
62 //
63 // Note: In C++14 and later, this library is usable in a constexpr context.
64 //
65 // Example:
66 //
67 // // Valid in C++14
68 // constexpr absl::CivilDay cd(1969, 07, 20);
69
70 #ifndef ABSL_TIME_CIVIL_TIME_H_
71 #define ABSL_TIME_CIVIL_TIME_H_
72
73 #include <string>
74
75 #include "absl/strings/string_view.h"
76 #include "absl/time/internal/cctz/include/cctz/civil_time.h"
77
78 namespace absl {
79 ABSL_NAMESPACE_BEGIN
80
81 namespace time_internal {
82 struct second_tag : cctz::detail::second_tag {};
83 struct minute_tag : second_tag, cctz::detail::minute_tag {};
84 struct hour_tag : minute_tag, cctz::detail::hour_tag {};
85 struct day_tag : hour_tag, cctz::detail::day_tag {};
86 struct month_tag : day_tag, cctz::detail::month_tag {};
87 struct year_tag : month_tag, cctz::detail::year_tag {};
88 } // namespace time_internal
89
90 // -----------------------------------------------------------------------------
91 // CivilSecond, CivilMinute, CivilHour, CivilDay, CivilMonth, CivilYear
92 // -----------------------------------------------------------------------------
93 //
94 // Each of these civil-time types is a simple value type with the same
95 // interface for construction and the same six accessors for each of the civil
96 // time fields (year, month, day, hour, minute, and second, aka YMDHMS). These
97 // classes differ only in their alignment, which is indicated by the type name
98 // and specifies the field on which arithmetic operates.
99 //
100 // CONSTRUCTION
101 //
102 // Each of the civil-time types can be constructed in two ways: by directly
103 // passing to the constructor up to six integers representing the YMDHMS fields,
104 // or by copying the YMDHMS fields from a differently aligned civil-time type.
105 // Omitted fields are assigned their minimum valid value. Hours, minutes, and
106 // seconds will be set to 0, month and day will be set to 1. Since there is no
107 // minimum year, the default is 1970.
108 //
109 // Examples:
110 //
111 // absl::CivilDay default_value; // 1970-01-01 00:00:00
112 //
113 // absl::CivilDay a(2015, 2, 3); // 2015-02-03 00:00:00
114 // absl::CivilDay b(2015, 2, 3, 4, 5, 6); // 2015-02-03 00:00:00
115 // absl::CivilDay c(2015); // 2015-01-01 00:00:00
116 //
117 // absl::CivilSecond ss(2015, 2, 3, 4, 5, 6); // 2015-02-03 04:05:06
118 // absl::CivilMinute mm(ss); // 2015-02-03 04:05:00
119 // absl::CivilHour hh(mm); // 2015-02-03 04:00:00
120 // absl::CivilDay d(hh); // 2015-02-03 00:00:00
121 // absl::CivilMonth m(d); // 2015-02-01 00:00:00
122 // absl::CivilYear y(m); // 2015-01-01 00:00:00
123 //
124 // m = absl::CivilMonth(y); // 2015-01-01 00:00:00
125 // d = absl::CivilDay(m); // 2015-01-01 00:00:00
126 // hh = absl::CivilHour(d); // 2015-01-01 00:00:00
127 // mm = absl::CivilMinute(hh); // 2015-01-01 00:00:00
128 // ss = absl::CivilSecond(mm); // 2015-01-01 00:00:00
129 //
130 // Each civil-time class is aligned to the civil-time field indicated in the
131 // class's name after normalization. Alignment is performed by setting all the
132 // inferior fields to their minimum valid value (as described above). The
133 // following are examples of how each of the six types would align the fields
134 // representing November 22, 2015 at 12:34:56 in the afternoon. (Note: the
135 // string format used here is not important; it's just a shorthand way of
136 // showing the six YMDHMS fields.)
137 //
138 // absl::CivilSecond : 2015-11-22 12:34:56
139 // absl::CivilMinute : 2015-11-22 12:34:00
140 // absl::CivilHour : 2015-11-22 12:00:00
141 // absl::CivilDay : 2015-11-22 00:00:00
142 // absl::CivilMonth : 2015-11-01 00:00:00
143 // absl::CivilYear : 2015-01-01 00:00:00
144 //
145 // Each civil-time type performs arithmetic on the field to which it is
146 // aligned. This means that adding 1 to an absl::CivilDay increments the day
147 // field (normalizing as necessary), and subtracting 7 from an absl::CivilMonth
148 // operates on the month field (normalizing as necessary). All arithmetic
149 // produces a valid civil time. Difference requires two similarly aligned
150 // civil-time objects and returns the scalar answer in units of the objects'
151 // alignment. For example, the difference between two absl::CivilHour objects
152 // will give an answer in units of civil hours.
153 //
154 // ALIGNMENT CONVERSION
155 //
156 // The alignment of a civil-time object cannot change, but the object may be
157 // used to construct a new object with a different alignment. This is referred
158 // to as "realigning". When realigning to a type with the same or more
159 // precision (e.g., absl::CivilDay -> absl::CivilSecond), the conversion may be
160 // performed implicitly since no information is lost. However, if information
161 // could be discarded (e.g., CivilSecond -> CivilDay), the conversion must
162 // be explicit at the call site.
163 //
164 // Examples:
165 //
166 // void UseDay(absl::CivilDay day);
167 //
168 // absl::CivilSecond cs;
169 // UseDay(cs); // Won't compile because data may be discarded
170 // UseDay(absl::CivilDay(cs)); // OK: explicit conversion
171 //
172 // absl::CivilDay cd;
173 // UseDay(cd); // OK: no conversion needed
174 //
175 // absl::CivilMonth cm;
176 // UseDay(cm); // OK: implicit conversion to absl::CivilDay
177 //
178 // NORMALIZATION
179 //
180 // Normalization takes invalid values and adjusts them to produce valid values.
181 // Within the civil-time library, integer arguments passed to the Civil*
182 // constructors may be out-of-range, in which case they are normalized by
183 // carrying overflow into a field of courser granularity to produce valid
184 // civil-time objects. This normalization enables natural arithmetic on
185 // constructor arguments without worrying about the field's range.
186 //
187 // Examples:
188 //
189 // // Out-of-range; normalized to 2016-11-01
190 // absl::CivilDay d(2016, 10, 32);
191 // // Out-of-range, negative: normalized to 2016-10-30T23
192 // absl::CivilHour h1(2016, 10, 31, -1);
193 // // Normalization is cumulative: normalized to 2016-10-30T23
194 // absl::CivilHour h2(2016, 10, 32, -25);
195 //
196 // Note: If normalization is undesired, you can signal an error by comparing
197 // the constructor arguments to the normalized values returned by the YMDHMS
198 // properties.
199 //
200 // COMPARISON
201 //
202 // Comparison between civil-time objects considers all six YMDHMS fields,
203 // regardless of the type's alignment. Comparison between differently aligned
204 // civil-time types is allowed.
205 //
206 // Examples:
207 //
208 // absl::CivilDay feb_3(2015, 2, 3); // 2015-02-03 00:00:00
209 // absl::CivilDay mar_4(2015, 3, 4); // 2015-03-04 00:00:00
210 // // feb_3 < mar_4
211 // // absl::CivilYear(feb_3) == absl::CivilYear(mar_4)
212 //
213 // absl::CivilSecond feb_3_noon(2015, 2, 3, 12, 0, 0); // 2015-02-03 12:00:00
214 // // feb_3 < feb_3_noon
215 // // feb_3 == absl::CivilDay(feb_3_noon)
216 //
217 // // Iterates all the days of February 2015.
218 // for (absl::CivilDay d(2015, 2, 1); d < absl::CivilMonth(2015, 3); ++d) {
219 // // ...
220 // }
221 //
222 // ARITHMETIC
223 //
224 // Civil-time types support natural arithmetic operators such as addition,
225 // subtraction, and difference. Arithmetic operates on the civil-time field
226 // indicated in the type's name. Difference operators require arguments with
227 // the same alignment and return the answer in units of the alignment.
228 //
229 // Example:
230 //
231 // absl::CivilDay a(2015, 2, 3);
232 // ++a; // 2015-02-04 00:00:00
233 // --a; // 2015-02-03 00:00:00
234 // absl::CivilDay b = a + 1; // 2015-02-04 00:00:00
235 // absl::CivilDay c = 1 + b; // 2015-02-05 00:00:00
236 // int n = c - a; // n = 2 (civil days)
237 // int m = c - absl::CivilMonth(c); // Won't compile: different types.
238 //
239 // ACCESSORS
240 //
241 // Each civil-time type has accessors for all six of the civil-time fields:
242 // year, month, day, hour, minute, and second.
243 //
244 // civil_year_t year()
245 // int month()
246 // int day()
247 // int hour()
248 // int minute()
249 // int second()
250 //
251 // Recall that fields inferior to the type's alignment will be set to their
252 // minimum valid value.
253 //
254 // Example:
255 //
256 // absl::CivilDay d(2015, 6, 28);
257 // // d.year() == 2015
258 // // d.month() == 6
259 // // d.day() == 28
260 // // d.hour() == 0
261 // // d.minute() == 0
262 // // d.second() == 0
263 //
264 // CASE STUDY: Adding a month to January 31.
265 //
266 // One of the classic questions that arises when considering a civil time
267 // library (or a date library or a date/time library) is this:
268 // "What is the result of adding a month to January 31?"
269 // This is an interesting question because it is unclear what is meant by a
270 // "month", and several different answers are possible, depending on context:
271 //
272 // 1. March 3 (or 2 if a leap year), if "add a month" means to add a month to
273 // the current month, and adjust the date to overflow the extra days into
274 // March. In this case the result of "February 31" would be normalized as
275 // within the civil-time library.
276 // 2. February 28 (or 29 if a leap year), if "add a month" means to add a
277 // month, and adjust the date while holding the resulting month constant.
278 // In this case, the result of "February 31" would be truncated to the last
279 // day in February.
280 // 3. An error. The caller may get some error, an exception, an invalid date
281 // object, or perhaps return `false`. This may make sense because there is
282 // no single unambiguously correct answer to the question.
283 //
284 // Practically speaking, any answer that is not what the programmer intended
285 // is the wrong answer.
286 //
287 // The Abseil time library avoids this problem by making it impossible to
288 // ask ambiguous questions. All civil-time objects are aligned to a particular
289 // civil-field boundary (such as aligned to a year, month, day, hour, minute,
290 // or second), and arithmetic operates on the field to which the object is
291 // aligned. This means that in order to "add a month" the object must first be
292 // aligned to a month boundary, which is equivalent to the first day of that
293 // month.
294 //
295 // Of course, there are ways to compute an answer the question at hand using
296 // this Abseil time library, but they require the programmer to be explicit
297 // about the answer they expect. To illustrate, let's see how to compute all
298 // three of the above possible answers to the question of "Jan 31 plus 1
299 // month":
300 //
301 // Example:
302 //
303 // const absl::CivilDay d(2015, 1, 31);
304 //
305 // // Answer 1:
306 // // Add 1 to the month field in the constructor, and rely on normalization.
307 // const auto normalized = absl::CivilDay(d.year(), d.month() + 1, d.day());
308 // // normalized == 2015-03-03 (aka Feb 31)
309 //
310 // // Answer 2:
311 // // Add 1 to month field, capping to the end of next month.
312 // const auto next_month = absl::CivilMonth(d) + 1;
313 // const auto last_day_of_next_month = absl::CivilDay(next_month + 1) - 1;
314 // const auto capped = std::min(normalized, last_day_of_next_month);
315 // // capped == 2015-02-28
316 //
317 // // Answer 3:
318 // // Signal an error if the normalized answer is not in next month.
319 // if (absl::CivilMonth(normalized) != next_month) {
320 // // error, month overflow
321 // }
322 //
323 using CivilSecond =
324 time_internal::cctz::detail::civil_time<time_internal::second_tag>;
325 using CivilMinute =
326 time_internal::cctz::detail::civil_time<time_internal::minute_tag>;
327 using CivilHour =
328 time_internal::cctz::detail::civil_time<time_internal::hour_tag>;
329 using CivilDay =
330 time_internal::cctz::detail::civil_time<time_internal::day_tag>;
331 using CivilMonth =
332 time_internal::cctz::detail::civil_time<time_internal::month_tag>;
333 using CivilYear =
334 time_internal::cctz::detail::civil_time<time_internal::year_tag>;
335
336 // civil_year_t
337 //
338 // Type alias of a civil-time year value. This type is guaranteed to (at least)
339 // support any year value supported by `time_t`.
340 //
341 // Example:
342 //
343 // absl::CivilSecond cs = ...;
344 // absl::civil_year_t y = cs.year();
345 // cs = absl::CivilSecond(y, 1, 1, 0, 0, 0); // CivilSecond(CivilYear(cs))
346 //
347 using civil_year_t = time_internal::cctz::year_t;
348
349 // civil_diff_t
350 //
351 // Type alias of the difference between two civil-time values.
352 // This type is used to indicate arguments that are not
353 // normalized (such as parameters to the civil-time constructors), the results
354 // of civil-time subtraction, or the operand to civil-time addition.
355 //
356 // Example:
357 //
358 // absl::civil_diff_t n_sec = cs1 - cs2; // cs1 == cs2 + n_sec;
359 //
360 using civil_diff_t = time_internal::cctz::diff_t;
361
362 // Weekday::monday, Weekday::tuesday, Weekday::wednesday, Weekday::thursday,
363 // Weekday::friday, Weekday::saturday, Weekday::sunday
364 //
365 // The Weekday enum class represents the civil-time concept of a "weekday" with
366 // members for all days of the week.
367 //
368 // absl::Weekday wd = absl::Weekday::thursday;
369 //
370 using Weekday = time_internal::cctz::weekday;
371
372 // GetWeekday()
373 //
374 // Returns the absl::Weekday for the given (realigned) civil-time value.
375 //
376 // Example:
377 //
378 // absl::CivilDay a(2015, 8, 13);
379 // absl::Weekday wd = absl::GetWeekday(a); // wd == absl::Weekday::thursday
380 //
GetWeekday(CivilSecond cs)381 inline Weekday GetWeekday(CivilSecond cs) {
382 return time_internal::cctz::get_weekday(cs);
383 }
384
385 // NextWeekday()
386 // PrevWeekday()
387 //
388 // Returns the absl::CivilDay that strictly follows or precedes a given
389 // absl::CivilDay, and that falls on the given absl::Weekday.
390 //
391 // Example, given the following month:
392 //
393 // August 2015
394 // Su Mo Tu We Th Fr Sa
395 // 1
396 // 2 3 4 5 6 7 8
397 // 9 10 11 12 13 14 15
398 // 16 17 18 19 20 21 22
399 // 23 24 25 26 27 28 29
400 // 30 31
401 //
402 // absl::CivilDay a(2015, 8, 13);
403 // // absl::GetWeekday(a) == absl::Weekday::thursday
404 // absl::CivilDay b = absl::NextWeekday(a, absl::Weekday::thursday);
405 // // b = 2015-08-20
406 // absl::CivilDay c = absl::PrevWeekday(a, absl::Weekday::thursday);
407 // // c = 2015-08-06
408 //
409 // absl::CivilDay d = ...
410 // // Gets the following Thursday if d is not already Thursday
411 // absl::CivilDay thurs1 = absl::NextWeekday(d - 1, absl::Weekday::thursday);
412 // // Gets the previous Thursday if d is not already Thursday
413 // absl::CivilDay thurs2 = absl::PrevWeekday(d + 1, absl::Weekday::thursday);
414 //
NextWeekday(CivilDay cd,Weekday wd)415 inline CivilDay NextWeekday(CivilDay cd, Weekday wd) {
416 return CivilDay(time_internal::cctz::next_weekday(cd, wd));
417 }
PrevWeekday(CivilDay cd,Weekday wd)418 inline CivilDay PrevWeekday(CivilDay cd, Weekday wd) {
419 return CivilDay(time_internal::cctz::prev_weekday(cd, wd));
420 }
421
422 // GetYearDay()
423 //
424 // Returns the day-of-year for the given (realigned) civil-time value.
425 //
426 // Example:
427 //
428 // absl::CivilDay a(2015, 1, 1);
429 // int yd_jan_1 = absl::GetYearDay(a); // yd_jan_1 = 1
430 // absl::CivilDay b(2015, 12, 31);
431 // int yd_dec_31 = absl::GetYearDay(b); // yd_dec_31 = 365
432 //
GetYearDay(CivilSecond cs)433 inline int GetYearDay(CivilSecond cs) {
434 return time_internal::cctz::get_yearday(cs);
435 }
436
437 // FormatCivilTime()
438 //
439 // Formats the given civil-time value into a string value of the following
440 // format:
441 //
442 // Type | Format
443 // ---------------------------------
444 // CivilSecond | YYYY-MM-DDTHH:MM:SS
445 // CivilMinute | YYYY-MM-DDTHH:MM
446 // CivilHour | YYYY-MM-DDTHH
447 // CivilDay | YYYY-MM-DD
448 // CivilMonth | YYYY-MM
449 // CivilYear | YYYY
450 //
451 // Example:
452 //
453 // absl::CivilDay d = absl::CivilDay(1969, 7, 20);
454 // std::string day_string = absl::FormatCivilTime(d); // "1969-07-20"
455 //
456 std::string FormatCivilTime(CivilSecond c);
457 std::string FormatCivilTime(CivilMinute c);
458 std::string FormatCivilTime(CivilHour c);
459 std::string FormatCivilTime(CivilDay c);
460 std::string FormatCivilTime(CivilMonth c);
461 std::string FormatCivilTime(CivilYear c);
462
463 // absl::ParseCivilTime()
464 //
465 // Parses a civil-time value from the specified `absl::string_view` into the
466 // passed output parameter. Returns `true` upon successful parsing.
467 //
468 // The expected form of the input string is as follows:
469 //
470 // Type | Format
471 // ---------------------------------
472 // CivilSecond | YYYY-MM-DDTHH:MM:SS
473 // CivilMinute | YYYY-MM-DDTHH:MM
474 // CivilHour | YYYY-MM-DDTHH
475 // CivilDay | YYYY-MM-DD
476 // CivilMonth | YYYY-MM
477 // CivilYear | YYYY
478 //
479 // Example:
480 //
481 // absl::CivilDay d;
482 // bool ok = absl::ParseCivilTime("2018-01-02", &d); // OK
483 //
484 // Note that parsing will fail if the string's format does not match the
485 // expected type exactly. `ParseLenientCivilTime()` below is more lenient.
486 //
487 bool ParseCivilTime(absl::string_view s, CivilSecond* c);
488 bool ParseCivilTime(absl::string_view s, CivilMinute* c);
489 bool ParseCivilTime(absl::string_view s, CivilHour* c);
490 bool ParseCivilTime(absl::string_view s, CivilDay* c);
491 bool ParseCivilTime(absl::string_view s, CivilMonth* c);
492 bool ParseCivilTime(absl::string_view s, CivilYear* c);
493
494 // ParseLenientCivilTime()
495 //
496 // Parses any of the formats accepted by `absl::ParseCivilTime()`, but is more
497 // lenient if the format of the string does not exactly match the associated
498 // type.
499 //
500 // Example:
501 //
502 // absl::CivilDay d;
503 // bool ok = absl::ParseLenientCivilTime("1969-07-20", &d); // OK
504 // ok = absl::ParseLenientCivilTime("1969-07-20T10", &d); // OK: T10 floored
505 // ok = absl::ParseLenientCivilTime("1969-07", &d); // OK: day defaults to 1
506 //
507 bool ParseLenientCivilTime(absl::string_view s, CivilSecond* c);
508 bool ParseLenientCivilTime(absl::string_view s, CivilMinute* c);
509 bool ParseLenientCivilTime(absl::string_view s, CivilHour* c);
510 bool ParseLenientCivilTime(absl::string_view s, CivilDay* c);
511 bool ParseLenientCivilTime(absl::string_view s, CivilMonth* c);
512 bool ParseLenientCivilTime(absl::string_view s, CivilYear* c);
513
514 namespace time_internal { // For functions found via ADL on civil-time tags.
515
516 // Streaming Operators
517 //
518 // Each civil-time type may be sent to an output stream using operator<<().
519 // The result matches the string produced by `FormatCivilTime()`.
520 //
521 // Example:
522 //
523 // absl::CivilDay d = absl::CivilDay(1969, 7, 20);
524 // std::cout << "Date is: " << d << "\n";
525 //
526 std::ostream& operator<<(std::ostream& os, CivilYear y);
527 std::ostream& operator<<(std::ostream& os, CivilMonth m);
528 std::ostream& operator<<(std::ostream& os, CivilDay d);
529 std::ostream& operator<<(std::ostream& os, CivilHour h);
530 std::ostream& operator<<(std::ostream& os, CivilMinute m);
531 std::ostream& operator<<(std::ostream& os, CivilSecond s);
532
533 } // namespace time_internal
534
535 ABSL_NAMESPACE_END
536 } // namespace absl
537
538 #endif // ABSL_TIME_CIVIL_TIME_H_
539