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.
CodePudding user response:
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.).