1

I`m using date library. I didn`t understand how to get difference between 2 time points in milliseconds?

date::time_of_day<std::chrono::milliseconds> time1;
date::time_of_day<std::chrono::milliseconds> time2;
// set some time...
auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(time2 - time1);
std::cout << diff.count() << " milliseconds" << std::endl;

Error:

no match for 'operator-' (operand types are 'date::time_of_day<std::chrono::duration<long long int, std::ratio<1, 1000> > >' {aka 'date::hh_mm_ss<std::chrono::duration<long long int, std::ratio<1, 1000> > >'} and 'date::time_of_day<std::chrono::duration<long long int, std::ratio<1, 1000> > >' {aka 'date::hh_mm_ss<std::chrono::duration<long long int, std::ratio<1, 1000> > >'})

Artem
  • 517
  • 1
  • 7
  • 24

1 Answers1

3

Late during the standardization process, time_of_day was renamed to hh_mm_ss. The time_of_day name still exists as a type alias to hh_mm_ss in date as a backwards compatibility helper.

hh_mm_ss<milliseconds> is just a {hours, minutes, seconds, milliseconds} data structure that is handy for getting the "fields" out of a milliseconds duration. This is especially useful for formatting. But it is not that useful as an arithmetic type (such as subtraction).

To do arithmetic, it is best to operate with durations (e.g. milliseconds) and time_points (e.g. sys_time<milliseconds>). For example:

auto time1 = sys_days{July/2/2021} + 12h + 15min + 3s + 45ms;
auto time2 = sys_days{July/2/2021} + 13h + 15min + 4s + 145ms;
auto diff = time2 - time1;
cout << diff << '\n';

Output:

3601100ms

In the above example, time1 and time2 have type date::sys_time<std::chrono::milliseconds> which itself is a type alias for std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>. And diff has type std::chrono::milliseconds.

Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577
  • How to convert existing `hh_mm_ss` variable to `sys_time`? – Artem Jul 02 '21 at 17:18
  • 1
    `hh_mm_ss` can be converted to the _duration_ `milliseconds` with explicit conversion syntax: `milliseconds x{hms};`. This will just be the sum of the fields within the `hh_mm_ss`. Then, if you really want to, you can convert that duration to a time_point with the same explicit conversion syntax: `sys_time tp{x};`. Note that this time point will have the value of `x` `milliseconds` after 1970-01-01 00:00:00.000 UTC (assuming `x` is positive). – Howard Hinnant Jul 02 '21 at 17:22
  • 1
    For handling "times without dates" see this post for different options: https://stackoverflow.com/a/64895694/576911 – Howard Hinnant Jul 02 '21 at 17:39