bhylu.com

Advertisements

C++ Date and Time with chrono

Add minutes and seconds through chrono conversions rather than silently mixing plain integer units.

How it works

chrono duration types carry a unit period in their type. Arithmetic can combine compatible durations while preserving the intended scale. duration_cast makes a potentially lossy conversion explicit; converting ninety seconds to whole minutes truncates rather than rounding to two. steady_clock measures intervals without calendar adjustments, while system_clock relates to wall-clock time. Calendar formatting and timezone databases have additional library requirements; this fixed duration fixture needs neither the current date nor a network service.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror chrono.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · chrono.cpp

#include <iostream>
#include <chrono>

int main() {
    using namespace std::chrono_literals;
    auto planned = 12min + 90s;
    std::cout << "Seconds: " << std::chrono::duration_cast<std::chrono::seconds>(planned).count() << '\n';
    std::cout << "Whole minutes: " << std::chrono::duration_cast<std::chrono::minutes>(planned).count() << '\n';
}

Expected result

Seconds: 810
Whole minutes: 13

Twelve minutes plus ninety seconds gives eight hundred ten seconds. The whole-minute conversion discards thirty seconds under this representation. A scheduling application needs a separate policy for rounding up, local civil times and daylight-saving transitions. The legacy ctime API can still appear in integrations, but avoid assuming that its static buffers and local timezone behaviour match a modern concurrent service.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.