diff --git a/Examples-and-Recipes.md b/Examples-and-Recipes.md index 0b80112..ee9fc0e 100644 --- a/Examples-and-Recipes.md +++ b/Examples-and-Recipes.md @@ -24,6 +24,30 @@ system_clock::time_point = day_point(ymd) + hours(h) + minutes(min) + seconds(s); ``` +Alternatively, using `struct tm` to hold the components: + +```c++ +// Ignores tm_isdst! +template +void to_time_point(const std::tm& t, + std::chrono::time_point& tp) +{ + using namespace std::chrono; + using namespace date; + // Component values (as obtained from an UI form, for example) + int y = t.tm_year + 1900; + auto ymd = year(y)/(t.tm_mon+1)/t.tm_mday; // Yields a year_month_day type + if (!ymd.ok()) + throw std::runtime_error("Invalid date"); + tp = day_point(ymd) + + hours(t.tm_hour) + minutes(t.tm_min) + seconds(t.tm_sec); +} + +std::chrono::system_clock::time_point tp; +std::tm components = {...}; +to_time_point(components, tp); +``` + ### Obtaining `y/m/d h:m:s` components from a `time_point` (by [ecorm](https://github.com/ecorm)) @@ -63,7 +87,7 @@ std::tm to_calendar_time(std::chrono::time_point tp) result.tm_min = tod.minutes().count(); result.tm_hour = tod.hours().count(); result.tm_mday = unsigned(ymd.day()); - result.tm_mon = unsigned(ymd.month()); + result.tm_mon = unsigned(ymd.month()) - 1u; // Zero-based! result.tm_year = int(ymd.year()) - 1900; result.tm_wday = unsigned(weekday); result.tm_yday = daysSinceJan1.count();