Home > Mobile >  Converting time to local zone time: issue with hh_ss_mm template args (C 14)
Converting time to local zone time: issue with hh_ss_mm template args (C 14)

Time:12-30

I'm using C 14 and the famous enter image description here

CodePudding user response:

This is chrono giving you a bad error message for a real problem: You are attempting to silently truncate a fine precision expression (lt - localDay) to a coarser precision (milliseconds).

The expression lt - localDay is a type that has precision of system_clock::duration, which is somewhere between microseconds and nanoseconds depending on your platform. This is true, even though the source (and thus the value) of chronoTime_gmt only has precision of seconds at run time.

The easiest fix is to recognize that anything coming from a tm is at best seconds precision by truncating to seconds precision early:

auto chronoTime_gmt = date::floor<std::chrono::seconds>                    
                          (std::chrono::system_clock::from_time_t(timeT_gmt));

Now chronoTime_gmt has type time_point<system_clock, seconds>. And therefore the later expression lt - localDay will also have type seconds, which will implicitly convert to the milliseconds precision of your hh_mm_ss.

A suggestion is to also use seconds for the template parameter of your hh_mm_ss since the milliseconds precision goes unused. This won't change correctness or performance of your code, but the reader of your code will no longer spend time wondering why you chose milliseconds and then didn't use it.

  • Related