[英]Does struct tm->tm_yday give correct value for leap year?
Say I want to get the days that have passed since Jan 1, would this return the correct value for leap years? 假设我想获得自1月1日起已经过去的日子,这会返回leap年的正确值吗?
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 reference http://www.cplusplus.com/reference/ctime/tm/ tm参考http://www.cplusplus.com/reference/ctime/tm/
Yes it would, if you initialize currtime
to the current time instead of leaving it uninitialized: 是的,如果您将
currtime
初始化为当前时间而不是未初始化的话,它将:
time_t currtime = time(0);
A better reference will (probably) be found on your machine as man localtime
. 最好在
man localtime
计算机上(当地时间)找到一个更好的参考。 Or you can read it here . 或者您可以在这里阅读。
Note that the field is documented as having the values 0-365 (inclusive), not 0-364, so it has 366 possible values. 请注意,该字段记录为具有0-365(含)值,而不是0-364,因此它具有366个可能的值。
是-它将返回365。1月1日将返回0,12月31日将返回364(非le年)和365(leap年)
Yes, and you can test it. 是的,您可以对其进行测试。 You're better off doing it with
gmtime
because localtime
involves time zones and time zones can throw off the day by a day and we don't need that complication. 您最好使用
gmtime
进行此操作,因为localtime
涉及时区,并且时区可以一天一天结束,并且我们不需要这种复杂性。
2000 was a leap year, and a tricky one, so it makes a good test. 2000年是a年,也是棘手的一年,因此它是一个很好的考验。 Unix epoch for midnight Jan 1st, 2000 UTC is 946684800 (30 years + 7 leap days from Jan 1st, 1970).
2000年1月1日午夜的Unix时代是946684800(从1970年1月1日起30年+ 7个leap日)。 So we move forward 31 + 28 days to Feb 29th.
因此,我们将前进31天和28天,直到2月29日。 We can use
gmtime
to get the day of year, and asctime
to verify we have the right date. 我们可以使用
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));
}
And we can see it works, Feb 29th, 2000 is the 59th (counting from 0) day of the year. 我们可以看到它起作用,2000年2月29日是一年中的第59天(从0开始算起)。
0 == Sat Jan 1 00:00:00 2000
59 == Tue Feb 29 00:00:00 2000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.