What are the different ways to get a timestamp in C++?

There are several ways to get a timestamp in C++.

  1. The time() function in the standard library is used to obtain the current system time stamp, which returns the number of seconds since January 1, 1970 0:00:00.
#include <ctime>
#include <iostream>

int main() {
    time_t timestamp = time(nullptr);
    std::cout << "Current timestamp: " << timestamp << std::endl;
    return 0;
}
  1. The system_clock::now() function in the standard library is used to retrieve the current timestamp of the system, returning the number of milliseconds since January 1, 1970, 0:00:00.
#include <chrono>
#include <iostream>

int main() {
    auto timestamp = std::chrono::system_clock::now().time_since_epoch().count();
    std::cout << "Current timestamp: " << timestamp << std::endl;
    return 0;
}
  1. Retrieve timestamps using the API provided by the operating system, such as the GetSystemTime() function for Windows and the gettimeofday() function for Linux.
#include <iostream>
#include <windows.h>

int main() {
    SYSTEMTIME st;
    GetSystemTime(&st);
    FILETIME ft;
    SystemTimeToFileTime(&st, &ft);
    ULARGE_INTEGER ul;
    ul.LowPart = ft.dwLowDateTime;
    ul.HighPart = ft.dwHighDateTime;
    time_t timestamp = ul.QuadPart / 10000000ULL - 11644473600ULL;
    std::cout << "Current timestamp: " << timestamp << std::endl;
    return 0;
}
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds