Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Lấy thời gian hiện tại (date/time) trong C++

C++ có nhiều cách lấy thời gian, từ C-style (<ctime>) đến C++11 <chrono> hiện đại.

1. C-style (ctime) - Đơn giản, cũ

#include <iostream>
#include <ctime>

int main() {
    std::time_t now = std::time(nullptr);
    char* dt = std::ctime(&now); // Format cố định: "Wed Oct 3 08:35:24 2018\n"
    
    std::cout << "Local time: " << dt;
    return 0;
}

Kết quả

Local time: Wed Oct 3 08:35:24 2018

Tùy chỉnh format với strftime

char buffer[80];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
std::cout << "Formatted: " << buffer << '\n'; // 2018-10-03 08:35:24

2. C++11 - Hiện đại, type-safe, chính xác cao

#include <iostream>
#include <chrono>
#include <iomanip>
#include <ctime>

int main() {
    auto now = std::chrono::system_clock::now();
    
    // Chuyển sang time_t để format
    std::time_t now_c = std::chrono::system_clock::to_time_t(now);
    std::cout << "ctime: " << std::ctime(&now_c);
    
    // Format thủ công với chrono
    auto now_ms = std::chrono::time_point_cast(now);
    auto epoch = now_ms.time_since_epoch();
    auto ms = std::chrono::duration_cast(epoch).count() % 1000;
    
    std::tm local_tm = *std::localtime(&now_c);
    std::cout << std::put_time(&local_tm, "%Y-%m-%d %H:%M:%S") << '.' << std::setfill('0') << std::setw(3) << ms << '\n';
    
    // Độ chính xác cao
    auto ns = std::chrono::high_resolution_clock::now();
    std::cout << "Nanoseconds since epoch: " << ns.time_since_epoch().count() << '\n';
    
    return 0;
}

3. C++20 - Format dễ dàng (Calendar & Timezone)

#include <chrono>
#include <format>
#include <iostream>

int main() {
    auto now = std::chrono::system_clock::now();
    
    // Format trực tiếp (C++20)
    std::cout << std::format("{:%Y-%m-%d %H:%M:%S}", now) << '\n';
    std::cout << std::format("{:%F %T %Z}", now) << '\n';
    
    // Timezone (C++20)
    // auto zoned = std::chrono::zoned_time{"Asia/Ho_Chi_Minh", now};
    // std::cout << std::format("{:%Y-%m-%d %H:%M:%S %Z}", zoned) << '\n';
    
    return 0;
}

So sánh

Khuyến nghị

  • C++20: Dùng std::chrono + std::format
  • C++11/14/17: chrono cho tính toán, strftime cho format
  • Legacy/C: ctime/strftime
  • Tránh ctime trong multi-thread (buffer static)
APIĐộ chính xácType-safeFormatTimezone
ctimeGiâyKhôngCố địnhLocal only
strftimeGiâyKhôngLinh hoạtLocal/UTC
chrono (C++11)NanosecondCóThủ côngHand-coded
chrono (C++20)NanosecondCóstd::formatIANA tzdb