Reputation: 3048
I have some code that uses Howard Hinnant's date Library to parse microsecond enabled timestamps:
std::string time_test = "13:45:04.747334";
std::istringstream input(time_test);
std::chrono::microseconds current_time;
input >> date::parse("%T", current_time);
This yields the microseconds since midnight but it is assumed that the microseconds.
Now I need to add it to the microseconds since epoch for today's local midnight but the library makes the localtime assuming that std::chrono::system_clock::now()
provides time in UTC.
How do get time since epoch calculated as local time?
Upvotes: 2
Views: 1602
Reputation: 218890
To deal with local time you will need to install the "date/tz.h"
library. This involves compiling one source file: tz.cpp and either allowing an automatic downloading the IANA timezone database, manually installing it yourself, or using your OS's copy (if available).
The easiest way to get the current local time is to combine system_clock::now()
with current_zone()
in an object called zoned_time
:
zoned_time zt{current_zone(), system_clock::now()};
current_zone()
returns a time_zone const*
to a time zone representing your computer's currently set local time zone. From zoned_time
you can get your local time:
auto local_tp = zt.get_local_time();
local_tp
is a chrono::time_point
, but offset from system_clock::time_point
by your time zone's current UTC offset. Then you can work with local_tp
just like you might work with system_clock::time_point
. For example, to get the local time of day:
auto tod = local_tp - floor<days>(local_tp);
tod
is just a chrono::duration
measuring the time since the local midnight.
Or if you have such a duration, such as the current_time
you parsed in in your question, you could add that to the local midnight:
auto tp = floor<days>(local_tp) + current_time;
Here, tp
would have the type local_time<microseconds>
. And local_time<duration>
is just a type-alias for chrono::time_point<local_t, duration>
.
How do get time since epoch calculated as local time?
This is a somewhat ambiguous question so I have not addressed it directly. However I'd be happy to try if you can clarify the question. The epoch is 1970-01-01 00:00:00 UTC, and the time duration since that instant is independent of any time zone.
To further elaborate, given the current local time (current_time
) and assuming we know the local date (e.g. 2020-12-16), we can form a zoned_time
that encapsulates both the local time and the UTC equivalent:
string time_test = "19:45:04.747334";
istringstream input(time_test);
chrono::microseconds current_time;
input >> date::parse("%T", current_time);
local_days today{2020_y/12/16};
zoned_time zt{current_zone(), today + current_time};
cout << format("%F %T %Z\n", zt);
cout << format("%F %T %Z\n", zt.get_sys_time());
Output:
2020-12-16 19:45:04.747334 EST
2020-12-17 00:45:04.747334 UTC
Upvotes: 2