我正在尝试创建一个获取当前日期,接受个人生日并计算其年龄的函数。我得到了当前的日期。现在我试图接受这个人的生日(通过个人传递给该功能)并将该人的生日值存储在名为str_bday的结构tm
变量中。程序编译,但是当我运行它时,我得到了这个:
Your last name is Smith
Sat Feb 8 16:04:05 2014
Your birthday is: 3/1/1940
Wed Dec 31 18:59:59 1969
v245-2%
当我打印出str_bday struct tm
变量时,我不明白为什么打印出他们的生日是1969年。有人能帮帮我吗。以下是此功能的代码:
char* calcage(char *individual, char *age)
{
time_t current_time;
char *c_time_string;
current_time = time(NULL);
c_time_string = ctime(¤t_time);
printf(c_time_string);
char *birthday = (char *)malloc(50*sizeof(char));
birthday = strrchr(individual, ',');
birthday++;
printf("Your birthday is: %s\n", birthday);
char *bmonth, *bday, *byear;
int numbmonth, numbday, numbyear;
bmonth = strtok(birthday, "/");
bday = strtok(NULL, "/");
byear = strtok(NULL, "/");
numbmonth = atoi(bmonth);
numbday = atoi(bday);
numbyear = atoi(byear);
struct tm str_bday;
time_t time_bday;
str_bday.tm_year = 2012;
time_bday = mktime(&str_bday);
printf(ctime(&time_bday));
}
答案 0 :(得分:1)
tm_year
将根据1900
设置年份。 (例如str_bday.tm_year = numbyear -1900;
)
另外,您应该按照以下mktime
的返回值进行检查。
if(time_bday == (time_t)-1)
printf("error");
如果在一年前返回错误,因为它基于1970年的许多系统。
必须自己处理,如果是这样的话。
测试代码
#include <stdio.h>
#include <time.h>
int main(){
struct tm str_bday = {0};
time_t time_bday;
str_bday.tm_year = 2012 - 1900;
str_bday.tm_mon = 3 - 1;
str_bday.tm_mday = 1;
time_bday = mktime(&str_bday);
if(time_bday == (time_t)-1)
printf("error\n");
else
printf("%s\n", ctime(&time_bday));//Thu Mar 01 00:00:00 2012
return 0;
}