c++ - 在 C++ 中将日期转换为 unix 时间戳

标签 c++ unix timestamp

正如一些转换那些 unix 时间戳的网站所说,

2013/05/07 05:01:00 (yyyy/mm/dd, hh:mm:ss) is 1367902860.

我在 C++ 中的做法是,时间戳与日期不同。 这是代码:

time_t rawtime;
struct tm * timeinfo;

int year=2013, month=5, day=7, hour = 5, min = 1, sec = 0;

/* get current timeinfo: */
time ( &rawtime ); //or: rawtime = time(0);
/* convert to struct: */
timeinfo = localtime ( &rawtime ); 

/* now modify the timeinfo to the given date: */
timeinfo->tm_year   = year - 1900;
timeinfo->tm_mon    = month - 1;    //months since January - [0,11]
timeinfo->tm_mday   = day;          //day of the month - [1,31] 
timeinfo->tm_hour   = hour;         //hours since midnight - [0,23]
timeinfo->tm_min    = min;          //minutes after the hour - [0,59]
timeinfo->tm_sec    = sec;          //seconds after the minute - [0,59]

/* call mktime: create unix time stamp from timeinfo struct */
date = mktime ( timeinfo );

printf ("Until the given date, since 1970/01/01 %i seconds have passed.\n", date);

得到的时间戳是

1367899260, but not 1367902860.

这里有什么问题?即使我改成hour-1或hour+1,也不匹配。编辑:是的,如果我将小时加 1,它就可以工作。之前也给分钟加了 1。

最佳答案

您必须使用 timegm() 而不是 mktime(),仅此而已。因为 mktime 是本地时间,timegm 是 UTC/GMT 时间。

Converting Between Local Times and GMT/UTC in C/C++

关于c++ - 在 C++ 中将日期转换为 unix 时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21679056/

相关文章:

php - 加载 php 模块时出错

linux - 使用 PID 文件杀死守护进程

php - 需要帮助在 PHP 中使用时间戳对数组进行排序

c++ - 可以使用隐式构造函数初始化具有此 vector 成员的类吗?

c++ - SetWindowLongPtr 不能正常工作

android - 如何在 Qt Android 应用程序上禁用屏幕保护程序

c++ - 如何打印 std::map<int, std::vector<int>>?

linux - 如何创建 cron 命令

postgresql - 通过在 postgresql 上索引时间戳列来加快搜索速度?

mysql查询选择昨天、今天和明天