C++ Logo

std-discussion

Advanced search

Negative durations

From: Alexander N. Savin <ASavin_at_[hidden]>
Date: Thu, 21 Aug 2025 17:53:14 +0000
Hi! I am new to this mailing list. Not sure if it's alive.

Consider the following code example:

       using namespace std::chrono;

       milliseconds mx{-900};
       milliseconds my{900};
       seconds sx = duration_cast<seconds>(mx);
       seconds sy = duration_cast<seconds>(my);

       std::cout << "milliseconds: " << (my - mx).count() << std::endl;
       std::cout << "seconds: " << (sy - sx).count() << std::endl;

The output will be:

       milliseconds: 1800
       seconds: 0

Now imagine that the negative and positive values above represent clock time points, before and after the epoch, for two clocks with different resolutions. In this regard, the output looks a bit strange.

When casting a higher precision (integral) duration to a lower precision duration, rounding occurs towards zero, for both negative and positive values (ticks). This means that nanoseconds (or whatever) are truncated for positive ticks and added (rounded up) for negative ticks. For negative ticks, this may change the date of a time point.

For example, assuming the epoch is 1970-01-01 00:00:00, we get:

       system_clock::to_time_t(1950-12-31 23:59:59.123) = 1951-01-01 00:00:00

Thus, system_clock::to_time_t cannot be safely used to determine the date before the epoch.

I understand that the standard doesn't explicitly state whether time_t can be negative, but system_clock::time_point::min() is negative in most implementations.

I would prefer duration_cast to use a mathematical floor rather than truncate for negative values. What do you think?


Received on 2025-08-21 17:53:25