C中的mktime()返回-1(总是)

时间:2013-12-03 14:36:17

标签: c datetime mktime

我在这里有一个片段:http://ideone.com/fywv3J

在此发布:

#include <stdio.h>
#include <time.h>

int gtime_to = 20131231;

int main() {
  time_t current_time, licence_expiry_time;
  struct tm licence_expiry_time_struct;
  memset(&licence_expiry_time_struct, 0, sizeof(struct tm));
  licence_expiry_time_struct.tm_mday = gtime_to % 100;                  // get the day
  licence_expiry_time_struct.tm_mon = ((gtime_to % 10000) / 100) - 1;   // get the month
  licence_expiry_time_struct.tm_year = gtime_to / 10000;                // get the year
  licence_expiry_time_struct.tm_hour = 0;
  licence_expiry_time_struct.tm_min = 0;
  licence_expiry_time_struct.tm_sec = 0;
  licence_expiry_time_struct.tm_wday = 0;
  licence_expiry_time_struct.tm_yday = 0;
  licence_expiry_time_struct.tm_isdst = -1;
  licence_expiry_time = mktime(&licence_expiry_time_struct);
  time(&current_time); 
  printf("date = %d, month = %d, year = %d\n", licence_expiry_time_struct.tm_mday, licence_expiry_time_struct.tm_mon, licence_expiry_time_struct.tm_year);
  printf("cur = %d, expiry = %d, diff = %d", current_time, licence_expiry_time, difftime(licence_expiry_time, current_time));
  return 0;
}

对于我尝试过的每个可能值, mktime()的输出为 -1

这就是这条线 cur = 1386084345, expiry = -1, diff = -25165824 其中到期的值不应为 -1 。谁能告诉我我做错了什么?

1 个答案:

答案 0 :(得分:3)

你的年份应该是自1900年以来的抵消。这很可能是罪魁祸首。

尝试:

licence_expiry_time_struct.tm_year = gtime_to / 10000 - 1900; 

一般情况下,使用mktime()时,强烈建议首先使用有效的tm结构(即通过调用localtime()),然后更改字段。