C++ 如何将时间转换为纪元时间?

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

How to convert a time into epoch time?

c++time

提问by user788171

Say I have a specific instant in time where I know the hour, minute, day, second, month, year, etc; how can I convert this epoch time (seconds since 1970)?

假设我有一个特定的时刻,我知道小时、分钟、日、秒、月、年等;我如何转换这个纪元时间(自 1970 年以来的秒数)?

I can't use Boost, so please don't suggest a Boost solution.

我不能使用 Boost,所以请不要建议 Boost 解决方案。

回答by Adam Rosenfield

Use the mktime(3)function. For example:

使用该mktime(3)功能。例如:

struct tm t = {0};  // Initalize to all 0's
t.tm_year = 112;  // This is year-1900, so 112 = 2012
t.tm_mon = 8;
t.tm_mday = 15;
t.tm_hour = 21;
t.tm_min = 54;
t.tm_sec = 13;
time_t timeSinceEpoch = mktime(&t);
// Result: 1347764053

回答by Laurent Winkler

On Linux, use timegm to avoid having your local time zone subtracted:

在 Linux 上,使用 timegm 避免减去本地时区:

struct tm tm;

// set tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min and tm.tm_sec

tm.tm_year -= 1900; // year start at 1900
tm.tm_mon--;        // months start at january
TIME_STAMP t = timegm(&tm);

回答by chrisaycock

mktime()can convert struct tminto seconds-since-Epoch.

mktime()可以转换struct tm为自纪元以来的秒数。

回答by ericcurtin

mktime and memset is most portable for me:

mktime 和 memset 对我来说是最便携的:

struct tm t;
memset(&t, 0, sizeof(tm)); // Initalize to all 0's
t.tm_year = 112; // This is year-1900, so 112 = 2012
t.tm_mon = 8;
t.tm_mday = 15;
t.tm_hour = 21;
t.tm_min = 54;
t.tm_sec = 13;
time_t time_since_epoch = mktime(&t);