I tried to get local time / UTC selectively in std::string.
- What I've tried:
(1) getting std::string for UTC works fine with std::format:
auto utc = std::chrono::system_clock::now();
std::string sTime = std::format("{:%H%M%S}", utc);
(2) and local time:
auto zoned = std::chrono::zoned_time{ "Asia/Seoul", std::chrono::system_clock::now() };
sTime = std::format("{:%H%M%S}", zoned);
- What I want to achieve:
But they have different types. How can I achieve a functionality like this?
bool b = true;
sTime = std::format("{:%H%M%S}", b? utc : zoned);
zoned_timehas two getters:It can do this because
zoned_timeis just a convenience data structure that holds{time_zone const*, sys_time}. If you ask it for thesys_time, it just returns what it has. If you ask it for thelocal_time, it uses thetime_zoneto change thesys_timeintolocal_time.And if you format a
zoned_timethen it formats local time.So:
Or wrap that up in a function for a one-liner:
Update
@starriet주녕차 makes a good observation in a comment below that when you want local time in
choose_timethatzonedis "good enough" as opposed tozoned.get_local_time().And in this particular example, the two are equivalent. However I thought it worthwhile to point out when
zonedis actually a superior choice:If the format specification asks for time zone abbreviation (
%Z) or time zone offset (%z), thenzoned(which has typezoned_time) has this information and can can supply it, andzoned.get_local_time()(which has typelocal_time) does not.Additionally
zoned.get_sys_time()can also format%Z(as "UTC") or%z(as "0000"). The type ofzoned.get_sys_time()issys_timeand has the semantics of Unix Time.Whereas
local_timehas the semantics of: It is a local time which has yet to be paired with atime_zone. Andzoned_timeis effectively that pairing.