C++ Date & Time

Working with dates and time in C++

⏰ What is Date & Time?

C++ provides libraries to work with dates and time. You can get current time, format dates, calculate time differences using ctime and chrono libraries.


#include <iostream>
#include <ctime>
using namespace std;

int main() {
    time_t now = time(0);
    cout << "Current time: " << ctime(&now);
    return 0;
}
                                    

Time Operations

📅

Current Time

Get the current date and time

time_t now = time(0);
cout << ctime(&now);
🎨

Format Time

Format time in custom ways

tm* timeinfo = localtime(&now);
cout << asctime(timeinfo);
⏱️

Time Calculation

Calculate time differences

auto start = chrono::high_resolution_clock::now();
// Some operation
auto end = chrono::high_resolution_clock::now();
🌍

Time Zones

Work with different time zones

tm* utc = gmtime(&now);
tm* local = localtime(&now);

🔹 Getting Current Time

The <chrono> library provides precise time‑point and duration facilities. std::chrono::system_clock::now() retrieves the current time, convertible to calendar representations. This is essential for logging, benchmarking, scheduling, and any time‑sensitive application logic.

#include <iostream>
#include <ctime>
using namespace std;

int main() {
    // Get current time
    time_t now = time(0);
    
    // Convert to string
    char* timeStr = ctime(&now);
    cout << "Current date and time: " << timeStr;
    
    // Get local time structure
    tm* timeinfo = localtime(&now);
    
    cout << "Year: " << (timeinfo->tm_year + 1900) << endl;
    cout << "Month: " << (timeinfo->tm_mon + 1) << endl;
    cout << "Day: " << timeinfo->tm_mday << endl;
    
    return 0;
}

Output:

Current date and time: Mon Jan 15 14:30:25 2024
Year: 2024
Month: 1
Day: 15

🔹 Custom Time Formatting

std::strftime formats time into human‑readable strings using specifiers like %Y for year. This allows locale‑aware customization, producing outputs such as YYYY‑MM‑DD or full textual dates. Consistent formatting is key for user interfaces, reports, and data interchange.

#include <iostream>
#include <ctime>
using namespace std;

int main() {
    time_t now = time(0);
    tm* timeinfo = localtime(&now);
    char buffer[100];
    
    // Different format examples
    strftime(buffer, 100, "%Y-%m-%d", timeinfo);
    cout << "Date (YYYY-MM-DD): " << buffer << endl;
    
    strftime(buffer, 100, "%H:%M:%S", timeinfo);
    cout << "Time (HH:MM:SS): " << buffer << endl;
    
    strftime(buffer, 100, "%A, %B %d, %Y", timeinfo);
    cout << "Full date: " << buffer << endl;
    
    return 0;
}

Output:

Date (YYYY-MM-DD): 2024-01-15
Time (HH:MM:SS): 14:30:25
Full date: Monday, January 15, 2024

🔹 Measuring Execution Time

Chrono’s high‑resolution clocks measure code execution duration accurately. By recording time points before and after an operation, developers profile performance bottlenecks. The result (2001 milliseconds) guides optimization efforts and ensures performance requirements are met.

#include <iostream>
#include <chrono>
#include <thread>
using namespace std;

int main() {
    // Start timing
    auto start = chrono::high_resolution_clock::now();
    
    // Simulate some work (sleep for 2 seconds)
    this_thread::sleep_for(chrono::seconds(2));
    
    // End timing
    auto end = chrono::high_resolution_clock::now();
    
    // Calculate duration
    auto duration = chrono::duration_cast<chrono::milliseconds>(end - start);
    
    cout << "Execution time: " << duration.count() << " milliseconds" << endl;
    
    return 0;
}

Output:

Execution time: 2001 milliseconds

🔹 Common Format Specifiers

strftime specifiers like %H (hour) and %M (minute) provide flexible time formatting. These codes are standardized across C and C++, ensuring portable and consistent output. Mastering specifiers allows tailoring date‑time strings to any application need.

Date Formats:

  • %Y - 4-digit year (2024)
  • %y - 2-digit year (24)
  • %m - Month as number (01-12)
  • %B - Full month name (January)
  • %b - Short month name (Jan)
  • %d - Day of month (01-31)
  • %A - Full weekday name (Monday)
  • %a - Short weekday name (Mon)

Time Formats:

  • %H - Hour (00-23)
  • %I - Hour (01-12)
  • %M - Minutes (00-59)
  • %S - Seconds (00-59)
  • %p - AM/PM

🧠 Test Your Knowledge

Which header file is needed for basic time functions in C++?