Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Unix timestamp with C++

How do I get a uint unix timestamp in C++? I've googled a bit and it seems that most methods are looking for more convoluted ways to represent time. Can't I just get it as a uint?

like image 810
2rs2ts Avatar asked May 16 '11 02:05

2rs2ts


People also ask

How do I get the current Unix timestamp?

To find the unix current timestamp use the %s option in the date command. The %s option calculates unix timestamp by finding the number of seconds between the current date and unix epoch.

How do I get the current UNIX timestamp in C#?

C# Program to Get the Unix Timestamp Using DateTimeOffset. Now. ToUnixTimeSeconds() Method.

How do you get seconds in C++?

time() : time() function returns the time since the Epoch(jan 1 1970) in seconds. Prototype / Syntax : time_t time(time_t *tloc); Return Value : On success, the value of time in seconds since the Epoch is returned, on error -1 is returned.

What is timestamp in C++?

timestamp, a C++ code which prints the current YMDHMS date as a timestamp. This is useful when documenting the run of a program. By including a timestamp, the output of the program will always contain a clear indication of when it was created.


1 Answers

C++20 introduced a guarantee that time_since_epoch is relative to the UNIX epoch, and cppreference.com gives an example that I've distilled to the relevant code, and changed to units of seconds rather than hours:

#include <iostream> #include <chrono>   int main() {     const auto p1 = std::chrono::system_clock::now();       std::cout << "seconds since epoch: "               << std::chrono::duration_cast<std::chrono::seconds>(                    p1.time_since_epoch()).count() << '\n'; } 

Using C++17 or earlier, time() is the simplest function - seconds since Epoch, which for Linux and UNIX at least would be the UNIX epoch. Linux manpage here.

The cppreference page linked above gives this example:

#include <ctime> #include <iostream>   int main() {     std::time_t result = std::time(nullptr);     std::cout << std::asctime(std::localtime(&result))               << result << " seconds since the Epoch\n"; } 
like image 171
Tony Delroy Avatar answered Oct 01 '22 20:10

Tony Delroy