C++ Basics: Round Negative Durations Deliberately
duration_cast truncates integral duration conversions toward zero. floor and ceil are better when a time bucket needs a defined rounding direction.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as chrono-floor-negative-durations-demo.cpp:
#include <array>
#include <chrono>
#include <iostream>
int main()
{
using namespace std::chrono;
for (const auto value : std::array{milliseconds{1500}, milliseconds{-1500}}) {
std::cout << value.count() << " ms: cast="
<< duration_cast<seconds>(value).count()
<< ", floor=" << floor<seconds>(value).count()
<< ", ceil=" << ceil<seconds>(value).count() << '\n';
}
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic chrono-floor-negative-durations-demo.cpp -o chrono-floor-negative-durations-demo &&
./chrono-floor-negative-durations-demoObserved output:
1500 ms: cast=1, floor=1, ceil=2
-1500 ms: cast=-1, floor=-2, ceil=-1Read the result
Positive 1500 milliseconds truncates and floors to one second. Negative 1500 milliseconds truncates to minus one, but floors to minus two. Ceil chooses the smallest whole-second value that is not less than the input.
Apply it carefully
Choose a rounding rule before grouping signed offsets into buckets. Truncation and floor agree for nonnegative values but differ below zero. These conversions change units, not time zones. Ensure the destination representation can hold the converted value; rounding is not an overflow check.
The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- chrono-floor-negative-durations-demo.cpp chrono-floor-negative-durations-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.