From 540cbc0008582ee5548cc02b5b521086fb4b8651 Mon Sep 17 00:00:00 2001 From: Howard Hinnant Date: Sun, 26 Apr 2020 14:03:54 -0400 Subject: [PATCH] Updated Examples and Recipes (markdown) --- Examples-and-Recipes.md | 47 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/Examples-and-Recipes.md b/Examples-and-Recipes.md index 77819a2..6eda81d 100644 --- a/Examples-and-Recipes.md +++ b/Examples-and-Recipes.md @@ -27,6 +27,7 @@ This page contains examples and recipes contributed by community members. Feel f - [How to convert to/from C++ Builder's TDate and TDateTime](#TDate) - [How to convert to/from QDate](#QDate) - [How to convert to/from Windows' FILETIME](#fILETIME) +- [How to convert to/from boost::posix_time::ptime](#ptime) - [Print out a compact calendar for the year](#calendar) - [Parsing unambiguous date time inside daylight transition](#parse_daylight_transition) - [`microfortnights`?! Are you serious?](#microfortnights) @@ -1724,6 +1725,52 @@ FILETIME system_clock_to_FILETIME(system_clock::time_point systemPoint) { return result; } ``` + +### How to convert to/from `boost::posix_time::ptime` +(by [Howard Hinnant](https://github.com/HowardHinnant)) + +`boost::posix_time::ptime` and `std::chrono::system_clock::time_point` represent the same thing in their respective libraries (boost and chrono). So it is nice to be able to convert between them. This is how to do it: + +```c++ +#include "boost/date_time/posix_time/posix_time.hpp" +#include "date/date.h" + +std::chrono::system_clock::time_point +to_system_clock(boost::posix_time::ptime const& pt) +{ + using namespace std::chrono; + auto const dt = pt - boost::posix_time::from_time_t(0); +#ifdef BOOST_DATE_TIME_HAS_NANOSECONDS + std::chrono::nanoseconds ns{dt.total_nanoseconds()}; + return system_clock::time_point{duration_cast(ns)}; +#else + std::chrono::microseconds us{dt.total_microseconds()}; + return system_clock::time_point{us}; +#endif +} + +boost::posix_time::ptime +to_ptime(std::chrono::system_clock::time_point const& st) +{ + using namespace date; + using namespace std::chrono; + auto sd = floor(st); + year_month_day ymd = sd; + hh_mm_ss hms{st - sd}; + auto y = int(ymd.year()); + auto m = unsigned(ymd.month()); + auto d = unsigned(ymd.day()); + auto h = hms.hours().count(); + auto M = hms.minutes().count(); + auto s = hms.seconds().count(); +#ifdef BOOST_DATE_TIME_HAS_NANOSECONDS + auto fs = nanoseconds(hms.subseconds()).count(); +#else + auto fs = duration_cast(hms.subseconds()).count(); +#endif + return {{y, m, d}, {h, M, s, fs}}; +} +``` ### Print out a compact calendar for the year