I'd like to manipulate local time dates and then compute the time span between them. Questions:
what is the best way to go from a zoned_time to his components (y,m,d,hh,mm,ss, etc...) and back (taking into account dst)?
what is the correct way to find the elapsing time between two zoned_times?
What I tried so far:
I found that I can get the now from clock and then compute a zoned_time. Manipulating this info is becoming a nightmare though.
I found on this answer that, Extract year/month/day etc. from std::chrono::time_point in C++
#include <chrono>
int
main()
{
using namespace std::chrono;
auto tp = zoned_time{current_zone(), system_clock::now()}.get_local_time();
auto dp = floor<days>(tp);
year_month_day ymd{dp};
hh_mm_ss time{floor<milliseconds>(tp-dp)};
auto y = ymd.year();
auto m = ymd.month();
auto d = ymd.day();
auto h = time.hours();
auto M = time.minutes();
auto s = time.seconds();
auto ms = time.subseconds();
}
this would allow for example to take the current date, and be able to set for example:
h = 5;
M = 0;
s = 0;
ms = 0;
and have the 5am of the current date, but how to convert this information back into a zoned_time? Obviously this doesn't work:
auto rec = zoned_time(current_zone(), y + m + d + h + M + s + ms);
This seems a good approximation:
auto rec = zoned_time(current_zone(), std::chrono::local_days{y / m / d} + h + M + s + ms);
if (tp_s == rec) std::cout << "equal" << std::endl;
else {
std::cout << "different" << std::endl;
std::cout << tp << "\t" << rec << std::endl;
}
but it prints:
different 2023-03-21 10:54:30.0128147 2023-03-21 10:54:30.012 GMT
aside the small difference in time, what is perplexing is the std::chrono::local_days{y / m / d} + h + M + s + ms
. It's not really clear if the addition means shifting by a time interval or setting the actual fields. It's quite different to add 5h if there is a DST in the middle, or setting the hours field to 5.
Finally, I'd like to find the true time interval between the two local times, and i think it's done by:
auto diff = duration_cast<chr::minutes>(tp_s.get_sys_time() - rec.get_sys_time());
so this should return the true time passed between the two points regardless the DST, while i'm not really understanding what this really represents:
auto diff = duration_cast<chr::minutes>(tp_s.get_local_time() - rec.get_local_time());