Get Unix timestamp with C++

谁都会走 提交于 2019-11-27 12:53:45

问题


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?


回答1:


time() is the simplest function - seconds since 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";
}



回答2:


#include<iostream>
#include<ctime>

int main()
{
    std::time_t t = std::time(0);  // t is an integer type
    std::cout << t << " seconds since 01-Jan-1970\n";
    return 0;
}



回答3:


The most common advice is wrong, you can't just rely on time(). That's used for relative timing: ISO C++ doesn't specify that 1970-01-01T00:00Z is time_t(0)

What's worse is that you can't easily figure it out, either. Sure, you can find the calendar date of time_t(0) with gmtime, but what are you going to do if that's 2000-01-01T00:00Z ? How many seconds were there between 1970-01-01T00:00Z and 2000-01-01T00:00Z? It's certainly no multiple of 60, due to leap seconds.




回答4:


#include <iostream>
#include <sys/time.h>

using namespace std;

int main ()
{
  unsigned long int sec= time(NULL);
  cout<<sec<<endl;
}



回答5:


Windows uses a different epoch and time units: see Convert Windows Filetime to second in Unix/Linux

What std::time() returns on Windows is (as yet) unknown to me (;-))




回答6:


I created a global define with more information:

#include <iostream>
#include <ctime>
#include <iomanip>

#define INFO std::cout << std::put_time(std::localtime(&time_now), "%y-%m-%d %OH:%OM:%OS") << " [INFO] " << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") >> "
#define ERROR std::cout << std::put_time(std::localtime(&time_now), "%y-%m-%d %OH:%OM:%OS") << " [ERROR] " << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") >> "

static std::time_t time_now = std::time(nullptr);

Use it like this:

INFO << "Hello world" << std::endl;
ERROR << "Goodbye world" << std::endl;

Sample output:

16-06-23 21:33:19 [INFO] src/main.cpp(main:6) >> Hello world
16-06-23 21:33:19 [ERROR] src/main.cpp(main:7) >> Goodbye world

Put these lines in your header file. I find this very useful for debugging, etc.




回答7:


As this is the first result on google and there's no C++11 answer yet, here's how to use std::chrono to do this:

    #include <chrono>

    ...

    using namespace std::chrono;
    int64_t timestamp = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();

Note that this answer doesn't guarantee that the epoch is 1/1/1970, but in practice it is very likely to be.



来源:https://stackoverflow.com/questions/6012663/get-unix-timestamp-with-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!