C++ 找出自 1/1/1970 过去多少秒

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4196153/
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 14:48:15  来源:igfitidea点击:

find how many seconds past since 1/1/1970

c++

提问by yonatan

I am looking for a function in C++ that calculates how many seconds have past from 1/1/1970 until today.

我在 C++ 中寻找一个函数来计算从 1/1/1970 到今天过去了多少秒。

回答by aschepler

#include <time.h>

time_t seconds_past_epoch = time(0);

Available on most operating systems.

在大多数操作系统上可用。

回答by David

time_t time(void) time_t time(time_t *ptr)

time_t 时间(无效) time_t 时间(time_t *ptr)

include: time.h

包括:time.h

Returns the number of seconds that have passed since midnight, 1st January 1970 GMT (or pm, 31st December 1969 EST). If the parameter is not NULL, the same value is stored in the location pointed to. Follow this link for information on the time_t type. The value returned may be used as a reliable measure of elapsed time, and may be passed to ctime() or conversion into a human-readable string.

返回自格林威治标准时间 1970 年 1 月 1 日午夜(或美国东部标准时间 1969 年 12 月 31 日下午)以来经过的秒数。如果参数不为 NULL,则在指向的位置存储相同的值。按照此链接获取有关 time_t 类型的信息。返回的值可以用作经过时间的可靠度量,并且可以传递给 ctime() 或转换为人类可读的字符串。

Example:

例子:

time_t t1=time(NULL);
do_something_long();
time_t t2=time(NULL);
printf("%d seconds elapsed\n", t2-t1);

time_t values are produced from the clock by time. time_t values are produced from y,m,d,h,m,s parts by mktime and timegm. time_t values are analysed into y,m,d,h,m,s by localtime and gmtime. time_t values are converted to readable strings by ctime.

time_t 值是按时间从时钟产生的。time_t 值由 mktime 和 timegm 从 y,m,d,h,m,s 部分生成。time_t 值按 localtime 和 gmtime 分析为 y,m,d,h,m,s。time_t 值由 ctime 转换为可读字符串。

回答by Dirk Eddelbuettel

See man mktime:

man mktime

#include <time.h>

time_t secsSinceEpoch = mktime(localtime(NULL));