假设我想要获取自1月1日以来经过的天数,这是否会返回闰年的正确值?
struct tm *now_tm;
struct timeval tv;
time_t currtime;
gettimeofday(&tv, NULL);
currtime=tv.tv_sec;
now_tm = localtime(&currtime);
int day = now_tm->tm_yday;tm参考http://www.cplusplus.com/reference/ctime/tm/
发布于 2017-02-15 07:21:43
是的,如果您将currtime初始化为当前时间,而不是将其保留为未初始化:
time_t currtime = time(0);更好的参考资料(可能)会在你的机器上找到,叫做man localtime。或者你可以用here阅读它。
请注意,该字段的记录值为0-365 (包括0-365),而不是0-364,因此它有366个可能的值。
发布于 2017-02-15 07:50:00
是的,你可以测试它。您最好使用gmtime,因为localtime涉及时区,而时区可以将一天的时间推迟一天,而我们不需要这种复杂性。
2000年是一个闰年,也是一个棘手的年份,所以它是一个很好的测试。Unix纪元为UTC 2000年1月1日午夜是946684800 (30年+1970年1月1日起的7个闰日)。所以我们向前推进31 + 28天到2月29日。我们可以使用gmtime来获取一年中的日期,使用asctime来验证我们是否拥有正确的日期。
#include <stdio.h>
#include <time.h>
int main() {
struct tm *date;
const int secs_per_day = 24 * 60 * 60;
/* Jan 1st, 2000 midnight UTC in Unix epoch.
30 years since Jan 1st, 1970.
Plus 7 leap days between Jan 1, 1970 and Jan 1, 2000.
Feb 29th 1972, 76, 82, 86, 92, and 96
*/
int days = (30 * 365) + 7;
time_t time = days * secs_per_day;
date = gmtime(&time);
printf("%d == %s", date->tm_yday, asctime(date));
/* Jump ahead to Feb 29th */
time += (31 + 28) * secs_per_day;
date = gmtime(&time);
printf("%d == %s", date->tm_yday, asctime(date));
}我们可以看到它起作用了,2000年2月29日是一年中的第59天(从0开始计算)。
0 == Sat Jan 1 00:00:00 2000
59 == Tue Feb 29 00:00:00 2000发布于 2017-02-15 07:26:17
是-它将返回365。1月1日将返回0,12月31日非闰年将返回364,闰年将返回365。
https://stackoverflow.com/questions/42237966
复制相似问题