Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I get the unix timestamp as a variable in C++?

I am trying to make an accurate program that tells you the time, but I can’t get the current Unix timestamp. Is there any way I can get the timestamp?

I tried using int time = std::chrono::steady_clock::now(); but that gives me an error, saying that ‘std::chrono’ has not been declared. By the way, I’m new to C++

Let me know if you have the answer.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try using std::time, it should be available in Dev C++ 5.11, but let me know if it also throws an error:

#include <iostream>
#include <ctime>
#include <cstddef> // Include the NULL macro

int main() {
    // Get the current time in seconds
    time_t now = std::time(NULL);

    // Convert the Unix timestamp to a tm struct
    tm *time = std::localtime(&now);

    // Print the current time and date
    std::cout << "The current time and date is " << time->tm_year + 1900
              << "-" << time->tm_mon + 1 << "-" << time->tm_mday
              << " " << time->tm_hour << ":" << time->tm_min
              << ":" << time->tm_sec << std::endl;

    return 0;
}

In this example, the std::time() function is called with a NULL argument to get the current time in seconds. The value returned by the std::time() function is then printed to the console using the std::cout object.

You can use the std::localtime() function to convert the Unix timestamp to a more human-readable format. This function returns a tm struct that contains the local time broken down into its component parts (year, month, day, hour, minute, etc.).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading