mirror of
https://github.com/HowardHinnant/date.git
synced 2025-08-04 21:24:26 +02:00
Updated Examples and Recipes (markdown)
@@ -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;
|
||||
}
|
||||
```
|
||||
<a name="ptime"></a>
|
||||
### 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<system_clock::duration>(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<days>(st);
|
||||
year_month_day ymd = sd;
|
||||
hh_mm_ss<system_clock::duration> 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<microseconds>(hms.subseconds()).count();
|
||||
#endif
|
||||
return {{y, m, d}, {h, M, s, fs}};
|
||||
}
|
||||
```
|
||||
|
||||
<a name="calendar"></a>
|
||||
### Print out a compact calendar for the year
|
||||
|
Reference in New Issue
Block a user