HowardHinnant / date

A date and time library based on the C++11/14/17 <chrono> header
Other
3.14k stars 677 forks source link

Print the local date YYYYMMDDHHSS of a zoned_time #774

Closed Laureu closed 1 year ago

Laureu commented 1 year ago

Hello Mr Howard Hinnant. Thank you for all your work on your timezones and date !

I have a zoned_time created from an UTC timestamp and a string timezone. How can I manage to print the YYYYMMDDHHSS format of the local place please ? I managed to get a string by using a code of you found on github, but I printed the utc informations. Here is what I tried:

auto utcDate = date::make_zoned("UTC", date::sys_seconds{std::chrono::seconds{timestamp}});
auto localDate = date::make_zoned(timezone, utcDate);

auto timepoint = std::chrono::time_point<std::chrono::system_clock>(std::chrono::seconds(localDate.get_sys_time().time_since_epoch().count()));
date::year_month_day ymd = date::floor<date::days>(localDate.get_sys_time());
date::hh_mm_ss hms = date::make_time(timepoint - date::sys_days(ymd));
int year = int(ymd.year());
int month = unsigned(ymd.month());
int day = unsigned(ymd.day());
int hour = hms.hours().count();
int minute = hms.minutes().count();
int second = hms.seconds().count();
std::string readableStartTime = fmt::format("{:04d}{:02d}{:02d}{:02d}{:02d}{:02d}", year, month, day, hour, minute, second);

I suppose my make_time usage from the zoned_time is wrong. What do you think about it ?

Thank you very much !

Laureu commented 1 year ago

I found out myself I could use get_local_time() instead of get_sys_time(). It was obvious, sorry !

Again thanks for all the libs !

HowardHinnant commented 1 year ago

Hi Laureu,

Yes, .get_local_time() is the answer. I also wanted to add that you can format that local time with date::format("%Y%m%d%H%M%S", tp) to get the desired string. Though the way you deconstructed timepoint into fields is also correct and is what date::format is doing under the hood.

Laureu commented 1 year ago

Thank you for the tip ! This will allow me to lighten my code