使用 C++ 获取 Unix 时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6012663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:20:35  来源:igfitidea点击:

Get Unix timestamp with C++

c++unixtimestampuint

提问by 2rs2ts

How do I get a uintunix 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?

如何uint在 C++ 中获得unix 时间戳?我用谷歌搜索了一下,似乎大多数方法都在寻找更复杂的方式来表示时间。我不能把它当作一个uint吗?

回答by Tony Delroy

C++20 introduced a guarantee that time_since_epochwill be relative to the UNIX epoch, and gives this example (distilled to relevant code, and in units of seconds rather than hours):

C++20 引入了一个time_since_epoch与 UNIX 时代相关的保证,并给出了这个例子(提炼为相关代码,以秒而不是小时为单位):

#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.

使用 C++17 或更早版本,time()是最简单的函数 - 自 Epoch 以来的秒数,对于 Linux 和 UNIX 至少将是 UNIX epoch。此处为Linux 联机帮助页。

The cppreference page linked above gives this example:

上面链接的 cppreference 页面给出了这个例子

#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";
}

回答by wilhelmtell

#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;
}

回答by MSalters

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:00Zis time_t(0)

最常见的建议是错误的,你不能仅仅依赖time(). 这用于相对时间:ISO C++ 没有指定1970-01-01T00:00Ztime_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:00Zand 2000-01-01T00:00Z? It's certainly no multiple of 60, due to leap seconds.

更糟糕的是,您也无法轻松弄清楚。当然,您可以找到time_t(0)with的日历日期gmtime,但是如果是,您将怎么办2000-01-01T00:00Z1970-01-01T00:00Z和之间有多少秒2000-01-01T00:00Z?由于闰秒,它肯定不是 60 的倍数。

回答by anijhaw

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

using namespace std;

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

回答by Tharwen

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

由于这是 google 上的第一个结果,而且还没有 C++20 答案,这里是如何使用 std::chrono 来做到这一点:

#include <chrono>

//...

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

In versions of C++ before 20, system_clock's epoch being Unix epoch is a de-facto convention, but it's not standardized. If you're not on C++20, use at your own risk.

在 20 之前的 C++ 版本中,system_clock 的纪元是 Unix 纪元是事实上的约定,但它没有标准化。如果您使用的不是 C++20,请自担风险。

回答by davecb

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

Windows 使用不同的纪元和时间单位:参见 Convert Windows Filetime to second in Unix/Linux

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

我不知道 std::time() 在 Windows 上返回的内容(迄今为止)(;-))

回答by xinthose

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.

将这些行放在您的头文件中。我发现这对于调试等非常有用。