⚙️ C++

Trabalhando com Data e Hora em C++: Um Guia Detalhado

Here is the translated HTML article in English, following all your rules. ```html

What is it and why? (a real-life analogy)

Imagine you are keeping a diary. You write down not only events, but also exactly when they happened: "Today, March 15, 2025, at 14:30 I finished reading a book." Without the date and time, your entries would turn into a meaningless list — you wouldn't know what came earlier or later, how much time passed between events, or when the next important task is due.

In programming, it's exactly the same. Any program that interacts with the real world deals with date and time:

  • Phone alarm — needs to know the current time and compare it with a set time.
  • Reminder calendar — stores event dates and can show what's happening tomorrow.
  • Banking system — records the exact time of each transaction.
  • Game — calculates how much time a player spent in a session.
💡 Main idea: Date and time are not just numbers on a screen. They are a way to measure, compare, and store moments of our lives. The computer does this using special tools that we will learn about today.

In C++, working with date and time is like working with a very precise clock that can not only show the current time but also calculate the difference between two moments, add days or hours, format the date into a human-readable form, and much more.

Theory: how it works internally

Before writing code, let's understand how the computer generally represents time. This will help avoid many mistakes in the future.

Unix Epoch (Unix Timestamp)

Most programming languages, including C++, use the Unix epoch — this is the number of seconds that have passed since January 1, 1970, 00:00:00 UTC (Coordinated Universal Time). Why 1970? Because that's when the Unix operating system was created, and developers agreed to count time from that point.

For example, the number 1 704 000 000 is the number of seconds that have passed from January 1, 1970, to some point in 2024. This is convenient for the computer: a single number that is easy to perform mathematical operations on — add, subtract, compare.

⚠️ Important: For a human, the number 1,704,000,000 means nothing. But the computer can easily convert it to "December 15, 2024, 14:20:00". This is exactly what formatting functions are for.

Data types for time in C++

In modern C++ (starting from the C++11 standard and especially C++20), there are several ways to work with time. We will look at two main approaches:

Approach Library When to use
Classic (C-style) <ctime> For simple tasks: get the current time, print the date, measure the difference in seconds.
Modern (C++11/20) <chrono> For complex tasks: working with different units (milliseconds, microseconds), precise measurements, calendar dates.

In this article, we will focus on the modern approach using the <chrono> library, as it is safer, more convenient, and is the industry standard. But we will also look at the classic method — it is still used in older projects.

Main components of chrono

The <chrono> library consists of three main parts:

  • Clock — the source of time. There are different types: system_clock (system time, which we see on the clock), steady_clock (monotonic clock that never goes backward — ideal for measurements), high_resolution_clock (the most accurate clock available on the computer).
  • Time Point — a specific point on the timeline. For example, "now" or "January 1, 2025, exactly at noon".
  • Duration — a time interval. For example, "5 seconds", "2 hours", "100 milliseconds".

These three components work together: you take a clock, get the current moment, then you can add a duration to it and get a new moment, or subtract one moment from another and get a duration.

Syntax in C++: all forms and variations

Let's go over the basic operations with date and time. We will use both the classic approach (<ctime>) and the modern one (<chrono>).

1. Getting the current time (classic way)

#include <iostream>
#include <ctime>  // include the library for working with time

int main() {
    // Get the current time as the number of seconds since 1970
    std::time_t current_time = std::time(nullptr);
    
    // Convert to a human-readable format
    char* readable_time = std::ctime(&current_time);
    
    std::cout << "Current time: " << readable_time;
    
    return 0;
}

Explanation:

  • std::time_t — a data type that stores the number of seconds. Usually, it's just an integer (long).
  • std::time(nullptr) — a function that returns the current time. If you pass nullptr, it simply returns the number.
  • std::ctime() — converts the number into a string like "Tue Dec 15 14:20:00 2024".

2. Getting the current time (modern way with chrono)

#include <iostream>
#include <chrono>  // include the chrono library
#include <ctime>   // for converting to a readable format

int main() {
    // Get the current time point from the system clock
    auto now = std::chrono::system_clock::now();
    
    // Convert the time point to time_t for formatting
    std::time_t current_time = std::chrono::system_clock::to_time_t(now);
    
    // Convert to a human-readable string
    char* readable_time = std::ctime(&current_time);
    
    std::cout << "Current time: " << readable_time;
    
    return 0;
}
```