From a654f04647c236eace60738300910caee7e61fac Mon Sep 17 00:00:00 2001 From: Howard Hinnant Date: Mon, 30 May 2016 14:53:07 -0400 Subject: [PATCH] Updated Examples and Recipes (markdown) --- Examples-and-Recipes.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/Examples-and-Recipes.md b/Examples-and-Recipes.md index 8567ce0..f7e375d 100644 --- a/Examples-and-Recipes.md +++ b/Examples-and-Recipes.md @@ -11,6 +11,7 @@ This page contains examples and recipes contributed by community members. Feel f - [Working with the ISO week-based year](#iso_week) - [2Gs Birthday](#birthday2gs) - [Calculating Ordinal Dates](#year_day) +- [Local time arithmetic](#local_arithmetic) - [Convert a time zone abbreviation into a time zone](#convert_by_timezone_abbreviation) - [Find all instances when a daylight savings shift is not 1 hour](#tz_search) - [How many timezones are using daylight saving?](#tz_daylight) @@ -436,6 +437,39 @@ An [ordinal date](https://en.wikipedia.org/wiki/Ordinal_date) consists of a year assert(ymd == year_month_day{sys_days{year/jan/0} + year_day}); } + +### Local time arithmetic +(by [Howard Hinnant](https://github.com/HowardHinnant)) + +It is generally accepted knowledge that doing time point arithmetic in "local time" is error prone because of UTC offset changes such as daylight saving time. For example when "springing forward" onto daylight saving time, the day is only 23 hours long instead of the normal 24. + +However this library can be used to correctly do such computations very easily. Below is code that prints out 9am for several days in the "America/New_York", both just before the DST transition, and just after: + + #include "tz.h" + #include + + int + main() + { + using namespace std::chrono; + using namespace date; + auto base = make_zoned("America/New_York", local_days{mar/11/2016} + 9h); + for (int i = 0; i < 4; ++i) + { + std::cout << format("%F %T %z", base) << '\n'; + base = base.get_local_time() + days{1}; + } + } + +This code outputs: + + 2016-03-11 09:00:00 -0500 + 2016-03-12 09:00:00 -0500 + 2016-03-13 09:00:00 -0400 + 2016-03-14 09:00:00 -0400 + +Note that the code simply gets the current local time, adds 1 day to it, and assigns that local time back into the `zoned_time`. As long as the newly computed local time is not ambiguous or non-existent, this code just works. And if the newly computed local time _is_ ambiguous or non-existent, an exception will be thrown. + ### Convert a time zone abbreviation into a time zone (by [Howard Hinnant](https://github.com/HowardHinnant))