0

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.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • what compiler and version? – Daniel A. White Dec 04 '22 at 20:11
  • I'm using Dev C++ IDE 5.11 – DaniSilva25 Dec 04 '22 at 20:12
  • You do have a `#include ` at the top of your code and you compiled with `-std=c++11` or higher, right? Many g++ compilers still default to C++ 98 without the -std flag. – selbie Dec 04 '22 at 20:17
  • If I remember correctly, Dev C++ defaults to C++98, or at least that was the case when I last used it about 10 years ago. You can [force it](https://stackoverflow.com/questions/16951376/how-to-change-mode-from-c98-mode-in-dev-c-to-a-mode-that-supports-c0x-ran) to use newer standards that support chrono, or stick to older libraries like the one I mentioned in the answer. – Tomasz Kasperczyk Dec 04 '22 at 20:25

1 Answers1

0

Not sure why you need to use Unix timestamp, since C++11 and higher has more convinient types and functions to work with time. But anyway, here is example of how it can be done in both new and old way, copied from here: https://en.cppreference.com/w/cpp/chrono/system_clock/to_time_t

#include <iostream>
#include <ctime>
#include <chrono>
#include <thread>
using namespace std::chrono_literals;
 
int main()
{
    // The old way
    std::time_t oldt = std::time(nullptr);
 
    std::this_thread::sleep_for(2700ms);
 
    // The new way
    std::time_t newt = std::chrono::system_clock::to_time_t(
                           std::chrono::system_clock::now());
 
    std::cout << "oldt-newt == " << oldt-newt << " s\n";
}

Pay attention, that system_clock is used here. It is the only clock that gets "wall clock" time. Other clocks, like steady_clock is undefined in terms of what it values means. I.e. it can be time from last reboot or time from program start or anything else, the only guarantee steady_clock has is that it is steadely increasing. At the same time system_clock can go back, e.g. when user chages it or when adjusting for day light saving.

sklott
  • 2,634
  • 6
  • 17