在 C++ 中将日期转换为 unix 时间戳 [英] Convert date to unix time stamp in c++

查看:129
本文介绍了在 C++ 中将日期转换为 unix 时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

As some websites that convert those unix time stamps say, the stamp of

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

我在 C++ 中的做法是,戳记与日期不同.代码如下:

The way I do it in C++, the stamp differs from the date. Here is the code:

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 到分钟.

What is the problem here? Even if I change to hour-1 or hour+1, it does not match. Well yes if i add 1 to hour, it works. previously also added 1 to minutes.

推荐答案

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

You must use timegm() instead of mktime(), and that's all. Because mktime is for localtime and timegm for UTC/GMT time.

在 C/中转换本地时间和 GMT/UTCC++

这篇关于在 C++ 中将日期转换为 unix 时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆